From 4c5c32118104cb23904b2d95de42d5330e6a94e1 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:02:37 -0800 Subject: [PATCH 1/8] =?UTF-8?q?feat(sql):=20`pgbot=20sql=20run`=20?= =?UTF-8?q?=E2=80=94=20run=20your=20own=20SQL=20read-only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Executes one or more statements inside a single BEGIN READ ONLY transaction that is always rolled back, so the server itself refuses writes and DDL. Before anything is sent, pgbot refuses statements that could end or escape the transaction (COMMIT/BEGIN/SAVEPOINT/…), reach outside the database (COPY, dblink, large-object file I/O) or act on other sessions or the server (pg_terminate_backend, pg_reload_conf, stats resets, replication slots, VACUUM, LOCK). Each statement goes over the extended protocol, so one call carries exactly one statement. Statement and lock timeouts bound every statement and --max-rows stops fetching server-side. Output is psql-style aligned text, or JSON with --json (sql_run_schema_version 1.0.0), which the desktop app's PSQL mode decodes. Tests: statement splitting (quotes, E'', dollar quoting, nested comments), the refusal list, the aligned renderer, the JSON contract, refusal before connecting, and an integration test (PGBOT_TEST_SUPERUSER_DSN) proving that writes and DDL never land even for a superuser, plus types, NULL, max-rows, statement timeout and error positions. Co-Authored-By: Claude Opus 5.5 --- cmd/pgbot/sql.go | 8 +- cmd/pgbot/sqlrun.go | 522 +++++++++++++++++++++++++++ cmd/pgbot/sqlrun_integration_test.go | 110 ++++++ cmd/pgbot/sqlrun_test.go | 178 +++++++++ 4 files changed, 815 insertions(+), 3 deletions(-) create mode 100644 cmd/pgbot/sqlrun.go create mode 100644 cmd/pgbot/sqlrun_integration_test.go create mode 100644 cmd/pgbot/sqlrun_test.go diff --git a/cmd/pgbot/sql.go b/cmd/pgbot/sql.go index 1c790c8..40e3a06 100644 --- a/cmd/pgbot/sql.go +++ b/cmd/pgbot/sql.go @@ -24,11 +24,13 @@ import ( func newSQLCmd() *cobra.Command { cmd := &cobra.Command{ Use: "sql", - Short: "Statement-level tools: explain a query's plan in plain language", - Long: "Tools that take one SQL statement rather than inspecting the whole database.\n" + - "Everything here is read-only: a statement is planned, never executed.", + Short: "Statement-level tools: explain a plan, or run your own SQL read-only", + Long: "Tools that take SQL rather than inspecting the whole database. Everything here is\n" + + "read-only: `explain` plans a statement without executing it; `run` executes inside\n" + + "a READ ONLY transaction that is always rolled back.", } cmd.AddCommand(newSQLExplainCmd()) + cmd.AddCommand(newSQLRunCmd()) return cmd } diff --git a/cmd/pgbot/sqlrun.go b/cmd/pgbot/sqlrun.go new file mode 100644 index 0000000..b5b86ea --- /dev/null +++ b/cmd/pgbot/sqlrun.go @@ -0,0 +1,522 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "regexp" + "sort" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/pgrundev/pgbot/internal/conn" + "github.com/pgrundev/pggo" + "github.com/spf13/cobra" +) + +// `pgbot sql run` executes the user's own SQL — the psql-style console of the +// desktop app — without giving up pgbot's read-only guarantee: +// +// - every statement runs inside ONE `BEGIN READ ONLY` transaction that is +// always rolled back, so the server itself refuses writes and DDL; +// - statements that could end or escape that transaction (COMMIT, BEGIN, +// SAVEPOINT, …), reach outside the database (COPY, dblink, large-object +// file I/O) or act on other sessions or the server (pg_terminate_backend, +// pg_reload_conf, stats resets, replication-slot changes, …) are refused +// before anything is sent; +// - each statement goes over the extended protocol, which carries exactly one +// statement, so "SELECT 1; COMMIT" cannot be smuggled into one call; +// - a statement timeout and a lock timeout bound every statement, and result +// sets are cut off server-side at --max-rows. +func newSQLRunCmd() *cobra.Command { + var f sqlRunFlags + cmd := &cobra.Command{ + Use: `run [connection-string] ""`, + Short: "Run your own SQL read-only (psql-style), as a table or JSON", + Long: "Executes one or more statements inside a single READ ONLY transaction that is\n" + + "always rolled back. Writes and DDL are refused by the server; transaction\n" + + "control, COPY, dblink, large-object file I/O and functions that act on other\n" + + "sessions or the server (pg_terminate_backend, pg_reload_conf, stats resets,\n" + + "replication-slot changes, …) are refused by pgbot before anything is sent.\n\n" + + "The SQL is the last argument, or stdin when piped. The connection is the first\n" + + "argument, else $DATABASE_URL / $PGBOT_DATABASE_URL / $PGSERVICE.", + Example: " pgbot sql run \"SELECT now()\"\n" + + " echo 'SELECT relname, n_live_tup FROM pg_stat_user_tables ORDER BY 2 DESC LIMIT 5;' | pgbot sql run --json", + Args: cobra.MaximumNArgs(2), + RunE: func(cmd *cobra.Command, args []string) error { return runSQLRun(cmd, args, f) }, + } + fl := cmd.Flags() + fl.BoolVar(&f.jsonOut, "json", false, "emit results as JSON (sql_run_schema_version 1.0.0)") + fl.IntVar(&f.maxRows, "max-rows", 500, "rows returned per statement; the rest are never fetched") + fl.DurationVar(&f.timeout, "statement-timeout", 30*time.Second, "per-statement timeout") + return cmd +} + +type sqlRunFlags struct { + jsonOut bool + maxRows int + timeout time.Duration +} + +const sqlRunSchemaVersion = "1.0.0" + +type sqlRunColumn struct { + Name string `json:"name"` + Type string `json:"type"` +} + +type sqlRunResult struct { + Statement string `json:"statement"` + Command string `json:"command"` + Columns []sqlRunColumn `json:"columns"` + Rows [][]*string `json:"rows"` + RowCount int `json:"row_count"` + Truncated bool `json:"truncated"` + ElapsedMS float64 `json:"elapsed_ms"` +} + +type sqlRunError struct { + StatementIndex int `json:"statement_index"` // 0-based; -1 when not tied to a statement + Statement string `json:"statement,omitempty"` + Message string `json:"message"` + SQLState string `json:"sqlstate,omitempty"` // "PGBOT" for a pgbot refusal + Detail string `json:"detail,omitempty"` + Hint string `json:"hint,omitempty"` + Position int `json:"position,omitempty"` // 1-based character offset into the statement +} + +type sqlRunOutput struct { + SchemaVersion string `json:"sql_run_schema_version"` + ReadOnly bool `json:"read_only"` + Results []sqlRunResult `json:"results"` + Error *sqlRunError `json:"error,omitempty"` + ElapsedMS float64 `json:"elapsed_ms"` +} + +func runSQLRun(cmd *cobra.Command, args []string, f sqlRunFlags) error { + if f.maxRows < 1 || f.maxRows > 100000 { + return usageErrf("--max-rows must be between 1 and 100000, got %d", f.maxRows) + } + connString, input, err := resolveSQLExplainInput(args, os.Stdin, isInteractive()) + if err != nil { + return err + } + out, err := executeSQLRun(cmd.Context(), connString, input, f) + if err != nil { + return err + } + return emitSQLRun(cmd.OutOrStdout(), f.jsonOut, out) +} + +// executeSQLRun does the work of `pgbot sql run` and returns the output +// document. A refusal or a statement error is reported in out.Error (with +// err nil); err is reserved for usage, connection and session failures. +// Everything is rolled back and the connection closed before it returns. +func executeSQLRun(ctx context.Context, connString, input string, f sqlRunFlags) (sqlRunOutput, error) { + out := sqlRunOutput{SchemaVersion: sqlRunSchemaVersion, ReadOnly: true, Results: []sqlRunResult{}} + started := time.Now() + finish := func() (sqlRunOutput, error) { + out.ElapsedMS = float64(time.Since(started).Microseconds()) / 1000 + return out, nil + } + + stmts := splitSQLStatements(input) + if len(stmts) == 0 { + return out, usageErrf("no SQL statement given") + } + for i, s := range stmts { + if reason := refuseStatement(s); reason != "" { + out.Error = &sqlRunError{StatementIndex: i, Statement: s, SQLState: "PGBOT", Message: reason, + Hint: "pgbot runs SQL read-only: queries and catalog lookups work; changes, transaction control and server actions don't."} + return finish() + } + } + + ctx, cancel := context.WithTimeout(ctx, time.Duration(len(stmts))*f.timeout+15*time.Second) + defer cancel() + target, err := conn.Connect(ctx, connString) + if err != nil { + return out, fmt.Errorf("connect: %s", conn.RedactConnString(err.Error())) + } + defer target.Close() + + tx, err := target.Pool.BeginTx(ctx, pggo.TxOptions{ReadOnly: true}) + if err != nil { + return out, fmt.Errorf("begin read-only transaction: %w", err) + } + // Always roll back: nothing here may persist, not even a SET. + defer func() { _ = tx.Rollback(context.Background()) }() + for _, s := range []string{ + fmt.Sprintf("SET LOCAL statement_timeout = %d", f.timeout.Milliseconds()), + "SET LOCAL lock_timeout = 5000", + "SET LOCAL idle_in_transaction_session_timeout = 60000", + } { + if _, err := tx.Exec(ctx, s); err != nil { + return out, fmt.Errorf("prepare session: %w", err) + } + } + + typeOIDs := map[uint32]bool{} + for i, s := range stmts { + res, err := runOneStatement(ctx, tx, s, f.maxRows) + if err != nil { + out.Error = toSQLRunError(i, s, err) + break + } + for _, c := range res.oids { + typeOIDs[c] = true + } + out.Results = append(out.Results, res.result) + } + // Type names come from the server's own catalog (format_type), resolved + // once for every column type seen. A failed statement aborts the + // transaction, so this is best-effort; numeric OIDs are the fallback. + names := map[uint32]string{} + if out.Error == nil && len(typeOIDs) > 0 { + names = typeNames(ctx, tx, typeOIDs) + } + for ri := range out.Results { + for ci := range out.Results[ri].Columns { + if oid, err := strconv.ParseUint(out.Results[ri].Columns[ci].Type, 10, 32); err == nil { + if n, ok := names[uint32(oid)]; ok { + out.Results[ri].Columns[ci].Type = n + } + } + } + } + return finish() +} + +type statementRun struct { + result sqlRunResult + oids []uint32 +} + +func runOneStatement(ctx context.Context, tx *pggo.Tx, stmt string, maxRows int) (statementRun, error) { + t0 := time.Now() + rows, err := tx.Query(ctx, stmt, pggo.MaxRows(maxRows)) + if err != nil { + return statementRun{}, err + } + defer rows.Close() + var run statementRun + cols := rows.Columns() + run.result.Statement = stmt + run.result.Columns = make([]sqlRunColumn, len(cols)) + for i, c := range cols { + run.result.Columns[i] = sqlRunColumn{Name: c.Name, Type: strconv.FormatUint(uint64(c.TypeOID), 10)} + run.oids = append(run.oids, c.TypeOID) + } + run.result.Rows = [][]*string{} + for rows.Next() { + raw := rows.RawValues() + row := make([]*string, len(raw)) + for i, v := range raw { + if v != nil { + s := string(v) + row[i] = &s + } + } + run.result.Rows = append(run.result.Rows, row) + } + if err := rows.Err(); err != nil { + return statementRun{}, err + } + run.result.RowCount = len(run.result.Rows) + run.result.Truncated = rows.Suspended() + run.result.Command = string(rows.CommandTag()) + if run.result.Command == "" && run.result.Truncated { + run.result.Command = fmt.Sprintf("SELECT %d", run.result.RowCount) // a suspended portal sends no tag + } + run.result.ElapsedMS = float64(time.Since(t0).Microseconds()) / 1000 + return run, nil +} + +func typeNames(ctx context.Context, tx *pggo.Tx, oids map[uint32]bool) map[uint32]string { + list := make([]string, 0, len(oids)) + for o := range oids { + list = append(list, strconv.FormatUint(uint64(o), 10)) + } + sort.Strings(list) + out := map[uint32]string{} + rows, err := tx.Query(ctx, "SELECT oid::int8, format_type(oid, NULL) FROM pg_type WHERE oid IN ("+strings.Join(list, ",")+")") + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + var oid int64 + var name string + if rows.Scan(&oid, &name) == nil { + out[uint32(oid)] = name + } + } + return out +} + +func toSQLRunError(i int, stmt string, err error) *sqlRunError { + var pe *pggo.PgError + if errors.As(err, &pe) { + e := &sqlRunError{StatementIndex: i, Statement: stmt, Message: pe.Message, SQLState: pe.Code, + Detail: pe.Detail, Hint: pe.Hint, Position: pe.Position} + switch pe.Code { + case "25006": // read_only_sql_transaction + e.Hint = "pgbot runs SQL read-only. Copy the statement and run it yourself if you mean to change the database." + case "57014": // query_canceled (statement_timeout) + e.Hint = "The statement hit pgbot's statement timeout. Narrow it (LIMIT, WHERE) or raise --statement-timeout." + } + return e + } + return &sqlRunError{StatementIndex: i, Statement: stmt, Message: conn.RedactConnString(err.Error())} +} + +func emitSQLRun(w io.Writer, jsonOut bool, out sqlRunOutput) error { + if jsonOut { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + if err := enc.Encode(out); err != nil { + return err + } + } else { + renderSQLRunText(w, os.Stderr, out) + } + if out.Error != nil { + os.Exit(exitFailure) // the output above already explains it + } + return nil +} + +// renderSQLRunText prints psql's "aligned" format: results to w, an error to errw. +func renderSQLRunText(w, errw io.Writer, out sqlRunOutput) { + for _, r := range out.Results { + if len(r.Columns) == 0 { + fmt.Fprintln(w, r.Command) + fmt.Fprintln(w) + continue + } + widths := make([]int, len(r.Columns)) + for i, c := range r.Columns { + widths[i] = utf8.RuneCountInString(c.Name) + } + cell := func(v *string) string { + if v == nil { + return "" + } + return strings.ReplaceAll(*v, "\n", "↵") + } + for _, row := range r.Rows { + for i, v := range row { + if n := utf8.RuneCountInString(cell(v)); n > widths[i] { + widths[i] = n + } + } + } + pad := func(s string, n int) string { return s + strings.Repeat(" ", n-utf8.RuneCountInString(s)) } + var head, rule []string + for i, c := range r.Columns { + head = append(head, " "+pad(c.Name, widths[i])+" ") + rule = append(rule, strings.Repeat("-", widths[i]+2)) + } + fmt.Fprintln(w, strings.Join(head, "|")) + fmt.Fprintln(w, strings.Join(rule, "+")) + for _, row := range r.Rows { + var cells []string + for i, v := range row { + cells = append(cells, " "+pad(cell(v), widths[i])+" ") + } + fmt.Fprintln(w, strings.Join(cells, "|")) + } + suffix := "s" + if r.RowCount == 1 { + suffix = "" + } + if r.Truncated { + fmt.Fprintf(w, "(first %d row%s; more were not fetched)\n\n", r.RowCount, suffix) + } else { + fmt.Fprintf(w, "(%d row%s)\n\n", r.RowCount, suffix) + } + } + if e := out.Error; e != nil { + fmt.Fprintf(errw, "ERROR: %s", e.Message) + if e.SQLState != "" && e.SQLState != "PGBOT" { + fmt.Fprintf(errw, " (SQLSTATE %s)", e.SQLState) + } + fmt.Fprintln(errw) + if e.Detail != "" { + fmt.Fprintln(errw, "DETAIL: "+e.Detail) + } + if e.Hint != "" { + fmt.Fprintln(errw, "HINT: "+e.Hint) + } + } +} + +// splitSQLStatements splits on top-level semicolons, respecting quoted strings +// ('…' with doubled-quote escapes, E'…' with backslash escapes), quoted identifiers, +// dollar-quoted bodies ($$…$$, $tag$…$tag$), and -- and nested /* */ comments. +// Empty and comment-only statements are dropped. +func splitSQLStatements(sql string) []string { + var out []string + var b strings.Builder + flush := func() { + s := strings.TrimSpace(b.String()) + if s != "" && strings.TrimSpace(stripSQLComments(s)) != "" { + out = append(out, s) + } + b.Reset() + } + rs := []rune(sql) + for i := 0; i < len(rs); i++ { + c := rs[i] + switch { + case c == '-' && i+1 < len(rs) && rs[i+1] == '-': + for i < len(rs) && rs[i] != '\n' { + b.WriteRune(rs[i]) + i++ + } + if i < len(rs) { + b.WriteRune(rs[i]) + } + case c == '/' && i+1 < len(rs) && rs[i+1] == '*': + depth := 0 + for i < len(rs) { + if rs[i] == '/' && i+1 < len(rs) && rs[i+1] == '*' { + depth++ + b.WriteString("/*") + i += 2 + continue + } + if rs[i] == '*' && i+1 < len(rs) && rs[i+1] == '/' { + depth-- + b.WriteString("*/") + i += 2 + if depth == 0 { + break + } + continue + } + b.WriteRune(rs[i]) + i++ + } + i-- + case c == '\'' || c == '"': + escapes := c == '\'' && i > 0 && (rs[i-1] == 'E' || rs[i-1] == 'e') && (i < 2 || !isIdentRune(rs[i-2])) + b.WriteRune(c) + for i++; i < len(rs); i++ { + b.WriteRune(rs[i]) + if escapes && rs[i] == '\\' && i+1 < len(rs) { + i++ + b.WriteRune(rs[i]) + continue + } + if rs[i] == c { + if i+1 < len(rs) && rs[i+1] == c { // doubled quote + i++ + b.WriteRune(rs[i]) + continue + } + break + } + } + case c == '$' && (i == 0 || !isIdentRune(rs[i-1])): + if tag, ok := dollarTag(rs, i); ok { + b.WriteString(tag) + i += utf8.RuneCountInString(tag) + end := strings.Index(string(rs[i:]), tag) + if end < 0 { + b.WriteString(string(rs[i:])) + i = len(rs) + break + } + body := string(rs[i:])[:end] + b.WriteString(body + tag) + i += utf8.RuneCountInString(body) + utf8.RuneCountInString(tag) - 1 + } else { + b.WriteRune(c) + } + case c == ';': + flush() + default: + b.WriteRune(c) + } + } + flush() + return out +} + +func isIdentRune(r rune) bool { + return r == '_' || r == '$' || (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r > 127 +} + +// dollarTag returns "$tag$" if one starts at rs[i]. +func dollarTag(rs []rune, i int) (string, bool) { + for j := i + 1; j < len(rs); j++ { + if rs[j] == '$' { + return string(rs[i : j+1]), true + } + if !(rs[j] == '_' || (rs[j] >= 'a' && rs[j] <= 'z') || (rs[j] >= 'A' && rs[j] <= 'Z') || (j > i+1 && rs[j] >= '0' && rs[j] <= '9') || rs[j] > 127) { + return "", false + } + } + return "", false +} + +var sqlCommentRE = regexp.MustCompile(`(?s)--[^\n]*|/\*.*?\*/`) + +func stripSQLComments(s string) string { return sqlCommentRE.ReplaceAllString(s, " ") } + +// refusedLeadingWords end or escape the read-only transaction, touch files or +// programs, or take locks / do maintenance that a console must not trigger. +var refusedLeadingWords = map[string]string{ + "begin": "transaction control", "start": "transaction control", "commit": "transaction control", + "end": "transaction control", "rollback": "transaction control", "abort": "transaction control", + "savepoint": "transaction control", "release": "transaction control", + "copy": "COPY reads or writes files and programs", "lock": "explicit table locks", + "vacuum": "maintenance", "analyze": "maintenance", "cluster": "maintenance", "reindex": "maintenance", + "checkpoint": "maintenance", "refresh": "maintenance", "discard": "session reset", + "listen": "notifications", "notify": "notifications", "unlisten": "notifications", +} + +// refusedFunctions act on other sessions, the server, replication, files, or +// reach other databases — none of which a read-only transaction prevents. +var refusedFunctions = []string{ + "pg_terminate_backend", "pg_cancel_backend", "pg_reload_conf", "pg_rotate_logfile", "pg_switch_wal", + "pg_promote", "pg_create_restore_point", "pg_wal_replay_pause", "pg_wal_replay_resume", + "pg_backup_start", "pg_backup_stop", "pg_start_backup", "pg_stop_backup", + "pg_create_physical_replication_slot", "pg_create_logical_replication_slot", "pg_drop_replication_slot", + "pg_replication_slot_advance", "pg_copy_physical_replication_slot", "pg_copy_logical_replication_slot", + "pg_logical_emit_message", "pg_stat_reset", "pg_stat_statements_reset", + "lo_import", "lo_export", "lo_unlink", "pg_file_write", "pg_file_rename", "pg_file_unlink", "pg_file_sync", + "dblink", "pg_background", +} + +var leadingWordRE = regexp.MustCompile(`^[\s(]*([A-Za-z]+)(?:\s+([A-Za-z]+))?`) + +// refuseStatement returns why a statement may not run, or "" if it may. +func refuseStatement(stmt string) string { + s := stripSQLComments(stmt) + if m := leadingWordRE.FindStringSubmatch(s); m != nil { + first, second := strings.ToLower(m[1]), strings.ToLower(m[2]) + if first == "prepare" && second == "transaction" { + return "PREPARE TRANSACTION is transaction control, which pgbot doesn't run" + } + if first == "set" && (second == "session" || second == "role" || second == "session_authorization") { + return "changing the session's role or characteristics isn't allowed" + } + if why, ok := refusedLeadingWords[first]; ok { + return fmt.Sprintf("%s (%s) isn't allowed in pgbot's read-only console", strings.ToUpper(first), why) + } + } + lower := strings.ToLower(s) + for _, fn := range refusedFunctions { + if strings.Contains(lower, fn) { + return fmt.Sprintf("%s acts outside this read-only transaction, so pgbot won't call it", fn) + } + } + return "" +} diff --git a/cmd/pgbot/sqlrun_integration_test.go b/cmd/pgbot/sqlrun_integration_test.go new file mode 100644 index 0000000..28b2cdb --- /dev/null +++ b/cmd/pgbot/sqlrun_integration_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "context" + "os" + "testing" + "time" + + "github.com/pgrundev/pggo" +) + +// TestIntegration_sqlRun proves `pgbot sql run` against a real server: rows and +// type names come back, NULL stays distinct from "", --max-rows stops fetching, +// the statement timeout fires — and above all that a write, even by a +// superuser, never lands. +func TestIntegration_sqlRun(t *testing.T) { + d := os.Getenv("PGBOT_TEST_SUPERUSER_DSN") + if d == "" { + t.Skip("set PGBOT_TEST_SUPERUSER_DSN to run the sql run integration test") + } + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + admin, err := pggo.Connect(ctx, d) + if err != nil { + t.Fatalf("admin connect: %v", err) + } + defer admin.Close() + if _, err := admin.SimpleQuery(ctx, `DROP TABLE IF EXISTS sqlrun_fixture; + CREATE TABLE sqlrun_fixture (id int PRIMARY KEY, note text); + INSERT INTO sqlrun_fixture SELECT g, CASE WHEN g % 2 = 0 THEN 'n' || g END FROM generate_series(1, 50) g`); err != nil { + t.Fatalf("setup: %v", err) + } + defer func() { _, _ = admin.Exec(context.Background(), `DROP TABLE IF EXISTS sqlrun_fixture`) }() + f := sqlRunFlags{maxRows: 500, timeout: 5 * time.Second} + + t.Run("rows, types and NULL", func(t *testing.T) { + out, err := executeSQLRun(ctx, d, "select id, note from sqlrun_fixture where id <= 2 order by id; select 'x'::varchar(3) as v;", f) + if err != nil || out.Error != nil { + t.Fatalf("err=%v out.Error=%+v", err, out.Error) + } + if len(out.Results) != 2 { + t.Fatalf("want 2 results, got %d", len(out.Results)) + } + r := out.Results[0] + if r.Columns[0].Type != "integer" || r.Columns[1].Type != "text" || out.Results[1].Columns[0].Type != "character varying" { + t.Errorf("type names not resolved: %+v / %+v", r.Columns, out.Results[1].Columns) + } + if r.RowCount != 2 || r.Rows[0][1] != nil || r.Rows[1][1] == nil || *r.Rows[1][1] != "n2" { + t.Errorf("rows = %v", r.Rows) + } + if r.Command != "SELECT 2" || r.Truncated { + t.Errorf("command=%q truncated=%v", r.Command, r.Truncated) + } + }) + + t.Run("max rows stops fetching", func(t *testing.T) { + g := f + g.maxRows = 10 + out, err := executeSQLRun(ctx, d, "select id from sqlrun_fixture order by id", g) + if err != nil || out.Error != nil { + t.Fatalf("err=%v out.Error=%+v", err, out.Error) + } + if r := out.Results[0]; r.RowCount != 10 || !r.Truncated { + t.Errorf("row_count=%d truncated=%v, want 10/true", r.RowCount, r.Truncated) + } + }) + + t.Run("writes and DDL are refused by the server and never land", func(t *testing.T) { + for _, stmt := range []string{ + "delete from sqlrun_fixture", + "update sqlrun_fixture set note = 'x'", + "insert into sqlrun_fixture values (999, 'x')", + "drop table sqlrun_fixture", + "create table sqlrun_should_not_exist (a int)", + "select 1; delete from sqlrun_fixture", + } { + out, err := executeSQLRun(ctx, d, stmt, f) + if err != nil { + t.Fatalf("%q: %v", stmt, err) + } + if out.Error == nil || out.Error.SQLState != "25006" { + t.Errorf("%q: want SQLSTATE 25006, got %+v", stmt, out.Error) + } + } + var n int + var exists bool + if err := admin.QueryRow(ctx, `SELECT count(*), to_regclass('sqlrun_should_not_exist') IS NOT NULL FROM sqlrun_fixture`).Scan(&n, &exists); err != nil { + t.Fatal(err) + } + if n != 50 || exists { + t.Fatalf("SAFETY VIOLATION: fixture has %d rows (want 50), stray table exists=%v", n, exists) + } + }) + + t.Run("statement timeout and a syntax error position", func(t *testing.T) { + g := f + g.timeout = 300 * time.Millisecond + out, err := executeSQLRun(ctx, d, "select pg_sleep(5)", g) + if err != nil || out.Error == nil || out.Error.SQLState != "57014" { + t.Errorf("want 57014, got err=%v %+v", err, out.Error) + } + out, err = executeSQLRun(ctx, d, "select 1; selec 2", f) + if err != nil || out.Error == nil || out.Error.SQLState != "42601" || out.Error.StatementIndex != 1 || out.Error.Position != 1 { + t.Errorf("want 42601 at statement 1 position 1, got err=%v %+v", err, out.Error) + } + if len(out.Results) != 1 { + t.Errorf("the statement before the error still reports, got %d results", len(out.Results)) + } + }) +} diff --git a/cmd/pgbot/sqlrun_test.go b/cmd/pgbot/sqlrun_test.go new file mode 100644 index 0000000..972b2ce --- /dev/null +++ b/cmd/pgbot/sqlrun_test.go @@ -0,0 +1,178 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "reflect" + "strings" + "testing" + "time" +) + +func TestSplitSQLStatements(t *testing.T) { + cases := []struct { + in string + want []string + }{ + {"select 1; select 2;", []string{"select 1", "select 2"}}, + {"select ';' as semi; select 2", []string{"select ';' as semi", "select 2"}}, + {"select 'it''s; fine'", []string{"select 'it''s; fine'"}}, + {`select E'a\'; b'`, []string{`select E'a\'; b'`}}, + {`select "we;ird" from t`, []string{`select "we;ird" from t`}}, + {"do $$ begin perform 1; end $$; select 3", []string{"do $$ begin perform 1; end $$", "select 3"}}, + {"select $fn$ x; y $fn$, $1", []string{"select $fn$ x; y $fn$, $1"}}, + {"select 1 -- trailing; comment\n; select 2", []string{"select 1 -- trailing; comment", "select 2"}}, + {"/* a; /* nested; */ still */ select 1", []string{"/* a; /* nested; */ still */ select 1"}}, + {" ;; -- only a comment\n ;", nil}, + } + for _, c := range cases { + if got := splitSQLStatements(c.in); !reflect.DeepEqual(got, c.want) { + t.Errorf("split(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +func TestRefuseStatement(t *testing.T) { + allowed := []string{ + "select * from orders", + "SELECT case when x then 1 end FROM t", // END inside CASE is not transaction control + "with t as (select 1) select * from t", + "explain select 1", + "show work_mem", + "set local work_mem = '64MB'", + "select pg_size_pretty(pg_database_size(current_database()))", + "(select 1) union (select 2)", + } + for _, s := range allowed { + if r := refuseStatement(s); r != "" { + t.Errorf("refused %q: %s", s, r) + } + } + refused := []string{ + "commit", "END", "rollback", "begin read write", "start transaction", "savepoint a", "release a", + "prepare transaction 'x'", "copy orders to '/tmp/x'", "COPY (select 1) TO PROGRAM 'id'", + "lock table orders in access exclusive mode", "vacuum orders", "analyze orders", "checkpoint", + "set session authorization postgres", "set role postgres", + "select pg_terminate_backend(123)", "SELECT PG_CANCEL_BACKEND(1)", "select pg_reload_conf()", + "select pg_stat_reset()", "select pg_stat_statements_reset()", "select * from dblink('x', 'delete from t')", + "select lo_export(1, '/tmp/x')", "select pg_drop_replication_slot('s')", + "/* sneaky */ commit", " -- note\n ROLLBACK", + } + for _, s := range refused { + if refuseStatement(s) == "" { + t.Errorf("allowed %q, want refused", s) + } + } +} + +func TestRefusalMessageNamesTheStatement(t *testing.T) { + if r := refuseStatement("commit"); !strings.Contains(r, "COMMIT") { + t.Errorf("message %q should name COMMIT", r) + } +} + +func strp(s string) *string { return &s } + +func TestRenderSQLRunText(t *testing.T) { + out := sqlRunOutput{Results: []sqlRunResult{ + {Command: "SELECT 2", Columns: []sqlRunColumn{{Name: "id", Type: "integer"}, {Name: "note", Type: "text"}}, + Rows: [][]*string{{strp("1"), strp("a\nb")}, {strp("22"), nil}}, RowCount: 2}, + {Command: "SELECT 1", Columns: []sqlRunColumn{{Name: "x", Type: "text"}}, Rows: [][]*string{{strp("é")}}, RowCount: 1, Truncated: true}, + {Command: "SET"}, + }} + var w, errw bytes.Buffer + renderSQLRunText(&w, &errw, out) + want := " id | note \n" + + "----+------\n" + + " 1 | a↵b \n" + + " 22 | \n" + + "(2 rows)\n\n" + + " x \n" + + "---\n" + + " é \n" + + "(first 1 row; more were not fetched)\n\n" + + "SET\n\n" + if w.String() != want { + t.Errorf("aligned output:\n%s\nwant:\n%s", w.String(), want) + } + if errw.Len() != 0 { + t.Errorf("no error expected on stderr, got %q", errw.String()) + } +} + +func TestRenderSQLRunTextError(t *testing.T) { + var w, errw bytes.Buffer + renderSQLRunText(&w, &errw, sqlRunOutput{Error: &sqlRunError{Message: "cannot execute INSERT in a read-only transaction", + SQLState: "25006", Hint: "read-only"}}) + want := "ERROR: cannot execute INSERT in a read-only transaction (SQLSTATE 25006)\nHINT: read-only\n" + if errw.String() != want { + t.Errorf("stderr = %q, want %q", errw.String(), want) + } + errw.Reset() + renderSQLRunText(&w, &errw, sqlRunOutput{Error: &sqlRunError{Message: "refused", SQLState: "PGBOT"}}) + if strings.Contains(errw.String(), "SQLSTATE") { + t.Errorf("a pgbot refusal has no server SQLSTATE: %q", errw.String()) + } +} + +// The desktop app decodes this document (desktop/macos PSQL.swift). Renaming a +// key is a breaking change to sql_run_schema_version. +func TestSQLRunJSONContract(t *testing.T) { + out := sqlRunOutput{SchemaVersion: sqlRunSchemaVersion, ReadOnly: true, + Results: []sqlRunResult{{Statement: "select null", Command: "SELECT 1", + Columns: []sqlRunColumn{{Name: "n", Type: "text"}}, Rows: [][]*string{{nil}}, RowCount: 1}}, + Error: &sqlRunError{StatementIndex: 1, Message: "m", SQLState: "42601", Position: 8}} + b, err := json.Marshal(out) + if err != nil { + t.Fatal(err) + } + var got map[string]any + if err := json.Unmarshal(b, &got); err != nil { + t.Fatal(err) + } + for _, k := range []string{"sql_run_schema_version", "read_only", "results", "error", "elapsed_ms"} { + if _, ok := got[k]; !ok { + t.Errorf("missing top-level key %q in %s", k, b) + } + } + r := got["results"].([]any)[0].(map[string]any) + for _, k := range []string{"statement", "command", "columns", "rows", "row_count", "truncated", "elapsed_ms"} { + if _, ok := r[k]; !ok { + t.Errorf("missing result key %q", k) + } + } + if cell := r["rows"].([]any)[0].([]any)[0]; cell != nil { + t.Errorf("NULL must encode as JSON null, got %#v", cell) + } + e := got["error"].(map[string]any) + for _, k := range []string{"statement_index", "message", "sqlstate", "position"} { + if _, ok := e[k]; !ok { + t.Errorf("missing error key %q", k) + } + } + b, _ = json.Marshal(sqlRunOutput{Results: []sqlRunResult{}}) + if strings.Contains(string(b), `"error"`) { + t.Errorf("error must be omitted on success: %s", b) + } +} + +// A refused statement is reported before any connection is attempted: the +// connection string below points at a port nothing listens on. +func TestExecuteSQLRunRefusesBeforeConnecting(t *testing.T) { + f := sqlRunFlags{maxRows: 10, timeout: time.Second} + out, err := executeSQLRun(context.Background(), "postgres://nobody@127.0.0.1:1/none?connect_timeout=1", + "select 1; select pg_terminate_backend(1); select 2", f) + if err != nil { + t.Fatalf("a refusal is output, not an error: %v", err) + } + if out.Error == nil || out.Error.SQLState != "PGBOT" || out.Error.StatementIndex != 1 { + t.Fatalf("want a PGBOT refusal of statement 1, got %+v", out.Error) + } + if len(out.Results) != 0 { + t.Errorf("nothing may run when any statement is refused, got %d results", len(out.Results)) + } + if _, err := executeSQLRun(context.Background(), "postgres://x@127.0.0.1:1/x", " -- nothing\n;", f); err == nil { + t.Error("comment-only input should be a usage error") + } +} From 13a931c08a11461ebe8514f5644b06ed972ff2de Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:03:35 -0800 Subject: [PATCH 2/8] =?UTF-8?q?feat(desktop):=20PGBotKit=20=E2=80=94=20cor?= =?UTF-8?q?e=20of=20the=20native=20macOS=20app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The headless half of PGBot for macOS (desktop/macos), with no SwiftUI so all of it is checkable from the command line: - Engine adapter over the bundled pgbot binary: typed calls for inspect, ask, sql explain, sql run, logs, activity, why, diff and init. The DSN goes in PGBOT_DATABASE_URL and SQL over stdin (never argv), the child environment is allow-listed, stderr is redacted, and runs are bounded by a timeout, SIGTERM→SIGKILL cancellation and a concurrency limit. - Codable mirror of the Context JSON contract, the engine's health-score formula with a completeness gate, and the id+object finding diff with an announcement ledger so a finding is never re-announced. - Keychain secrets (AfterFirstUnlockThisDeviceOnly), SQLite persistence (0600, no password field), a per-bot scheduler with backoff and sleep/wake, OAuth 2.0 + PKCE via an auth broker, and demo data. - PSQL mode: psql meta-commands (\d, \dt, \l, \dn, \df, \du, \dx, \x, …) translated to catalog queries with patterns quoted safely; shell, file and session commands refused. Checks: `swift run PGBotKitChecks` (49 unit checks; Command Line Tools ship no XCTest), plus 8 live checks with PGBOT_TEST_DSN and PGBOT_ENGINE_PATH. Co-Authored-By: Claude Opus 5.5 --- desktop/macos/.gitignore | 3 + desktop/macos/Package.swift | 24 + .../macos/Sources/PGBotKit/Auth/Auth.swift | 225 +++++++ .../Sources/PGBotKit/Demo/DemoData.swift | 216 ++++++ .../Sources/PGBotKit/Engine/AIProvider.swift | 76 +++ .../PGBotKit/Engine/EngineContext.swift | 523 ++++++++++++++ .../PGBotKit/Engine/EngineRunner.swift | 265 ++++++++ .../Sources/PGBotKit/Engine/PGBotEngine.swift | 167 +++++ .../Sources/PGBotKit/Models/HealthScore.swift | 99 +++ .../Sources/PGBotKit/Models/Models.swift | 398 +++++++++++ .../PGBotKit/Monitoring/FindingDiff.swift | 126 ++++ .../PGBotKit/Monitoring/ReportComposer.swift | 148 ++++ .../PGBotKit/Monitoring/Scheduler.swift | 121 ++++ .../macos/Sources/PGBotKit/PSQL/PSQL.swift | 312 +++++++++ .../Sources/PGBotKit/Persistence/Store.swift | 235 +++++++ .../PGBotKit/Security/ConnectionString.swift | 73 ++ .../Sources/PGBotKit/Security/Keychain.swift | 82 +++ .../Sources/PGBotKit/Security/Redactor.swift | 47 ++ desktop/macos/Tests/PGBotKitChecks/main.swift | 636 ++++++++++++++++++ 19 files changed, 3776 insertions(+) create mode 100644 desktop/macos/.gitignore create mode 100644 desktop/macos/Package.swift create mode 100644 desktop/macos/Sources/PGBotKit/Auth/Auth.swift create mode 100644 desktop/macos/Sources/PGBotKit/Demo/DemoData.swift create mode 100644 desktop/macos/Sources/PGBotKit/Engine/AIProvider.swift create mode 100644 desktop/macos/Sources/PGBotKit/Engine/EngineContext.swift create mode 100644 desktop/macos/Sources/PGBotKit/Engine/EngineRunner.swift create mode 100644 desktop/macos/Sources/PGBotKit/Engine/PGBotEngine.swift create mode 100644 desktop/macos/Sources/PGBotKit/Models/HealthScore.swift create mode 100644 desktop/macos/Sources/PGBotKit/Models/Models.swift create mode 100644 desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift create mode 100644 desktop/macos/Sources/PGBotKit/Monitoring/ReportComposer.swift create mode 100644 desktop/macos/Sources/PGBotKit/Monitoring/Scheduler.swift create mode 100644 desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift create mode 100644 desktop/macos/Sources/PGBotKit/Persistence/Store.swift create mode 100644 desktop/macos/Sources/PGBotKit/Security/ConnectionString.swift create mode 100644 desktop/macos/Sources/PGBotKit/Security/Keychain.swift create mode 100644 desktop/macos/Sources/PGBotKit/Security/Redactor.swift create mode 100644 desktop/macos/Tests/PGBotKitChecks/main.swift diff --git a/desktop/macos/.gitignore b/desktop/macos/.gitignore new file mode 100644 index 0000000..3210a44 --- /dev/null +++ b/desktop/macos/.gitignore @@ -0,0 +1,3 @@ +.build/ +build/ +.swiftpm/ diff --git a/desktop/macos/Package.swift b/desktop/macos/Package.swift new file mode 100644 index 0000000..f6a18df --- /dev/null +++ b/desktop/macos/Package.swift @@ -0,0 +1,24 @@ +// swift-tools-version:5.10 +// +// PGBot for macOS — a native SwiftUI front end over the existing pgbot Go engine. +// +// PGBotKit business logic: engine adapter, models, Keychain, SQLite +// persistence, monitoring scheduler, finding diff, redaction, +// OAuth/PKCE. No SwiftUI, so it is testable headless. +// PGBot the SwiftUI application (executable; bundled into PGBot.app +// by scripts/build-app.sh). +// PGBotKitChecks the test suite as an executable. Command Line Tools ship no +// XCTest, so `swift run PGBotKitChecks` is the portable runner. +import PackageDescription + +let package = Package( + name: "PGBotDesktop", + platforms: [.macOS(.v14)], + products: [ + .library(name: "PGBotKit", targets: ["PGBotKit"]), + ], + targets: [ + .target(name: "PGBotKit", path: "Sources/PGBotKit", linkerSettings: [.linkedLibrary("sqlite3")]), + .executableTarget(name: "PGBotKitChecks", dependencies: ["PGBotKit"], path: "Tests/PGBotKitChecks"), + ] +) diff --git a/desktop/macos/Sources/PGBotKit/Auth/Auth.swift b/desktop/macos/Sources/PGBotKit/Auth/Auth.swift new file mode 100644 index 0000000..035de1c --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Auth/Auth.swift @@ -0,0 +1,225 @@ +import CryptoKit +import Foundation + +// OAuth 2.0 authorization-code flow with PKCE (RFC 7636) for a public native +// client. The app holds NO client secret: Google and GitHub are reached through +// a small PGBot auth broker (`PGBotAuthBrokerURL` in Info.plist) that keeps the +// provider secrets server-side, verifies PKCE, and returns PGBot session tokens. +// The browser leg runs in the system browser (ASWebAuthenticationSession, in +// the app target); everything else is here and testable. + +public struct PKCE: Sendable, Equatable { + public let verifier: String + public let challenge: String + public static let method = "S256" + + public init(verifier: String) { + self.verifier = verifier + self.challenge = Self.base64url(Data(SHA256.hash(data: Data(verifier.utf8)))) + } + + /// 32 random bytes → a 43-char verifier (RFC 7636 §4.1 allows 43–128). + public static func generate() -> PKCE { PKCE(verifier: randomToken(bytes: 32)) } + + public static func randomToken(bytes: Int) -> String { + var g = SystemRandomNumberGenerator() + return base64url(Data((0.. String { + d.base64EncodedString().replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") + } +} + +public struct AuthConfiguration: Sendable, Equatable { + public var brokerURL: URL? + public var clientID: String + public var callbackScheme: String + public init(brokerURL: URL?, clientID: String = "pgbot-desktop", callbackScheme: String = "pgbot") { + self.brokerURL = brokerURL; self.clientID = clientID; self.callbackScheme = callbackScheme + } + public var isConfigured: Bool { brokerURL != nil } + public var redirectURI: String { "\(callbackScheme)://auth/callback" } + + public static func fromBundle(_ b: Bundle = .main) -> AuthConfiguration { + let raw = (b.object(forInfoDictionaryKey: "PGBotAuthBrokerURL") as? String) + ?? ProcessInfo.processInfo.environment["PGBOT_AUTH_BROKER_URL"] + let url = raw.flatMap { $0.isEmpty ? nil : URL(string: $0) } + // Refuse a non-TLS broker except on loopback (local development). + if let u = url, u.scheme != "https", !(u.host == "localhost" || u.host == "127.0.0.1") { + return AuthConfiguration(brokerURL: nil) + } + return AuthConfiguration(brokerURL: url) + } +} + +public struct AuthenticationSession: Codable, Sendable, Equatable { + public var user: User + public var accessToken: String + public var refreshToken: String? + public var expiresAt: Date + public var subscription: Subscription + public var isExpired: Bool { Date() >= expiresAt.addingTimeInterval(-60) } + public init(user: User, accessToken: String, refreshToken: String?, expiresAt: Date, subscription: Subscription) { + self.user = user; self.accessToken = accessToken; self.refreshToken = refreshToken + self.expiresAt = expiresAt; self.subscription = subscription + } +} + +public enum AuthError: LocalizedError, Equatable { + case notConfigured, cancelled, stateMismatch, missingCode, providerError(String), network(String), expired + public var errorDescription: String? { + switch self { + case .notConfigured: "Sign-in isn't configured in this build." + case .cancelled: "Sign-in was cancelled." + case .stateMismatch: "The sign-in response didn't match this request, so it was rejected for your safety. Please try again." + case .missingCode: "The sign-in response was incomplete. Please try again." + case .providerError(let s): "The provider declined sign-in: \(s)" + case .network(let s): "Couldn't reach the sign-in service: \(s)" + case .expired: "Your session expired. Please sign in again." + } + } +} + +/// One in-flight authorization request. +public struct AuthorizationRequest: Sendable { + public let provider: AuthProvider + public let pkce: PKCE + public let state: String + public let url: URL + + /// Validates the redirect and extracts the code. State is compared in + /// constant time; any mismatch aborts (CSRF / mix-up defense). + public func code(from callback: URL) throws -> String { + let items = URLComponents(url: callback, resolvingAgainstBaseURL: false)?.queryItems ?? [] + func v(_ n: String) -> String? { items.first { $0.name == n }?.value } + if let err = v("error") { throw AuthError.providerError(v("error_description") ?? err) } + guard let got = v("state"), constantTimeEqual(got, state) else { throw AuthError.stateMismatch } + guard let code = v("code"), !code.isEmpty else { throw AuthError.missingCode } + return code + } +} + +func constantTimeEqual(_ a: String, _ b: String) -> Bool { + let x = Array(a.utf8), y = Array(b.utf8) + guard x.count == y.count else { return false } + return zip(x, y).reduce(0) { $0 | ($1.0 ^ $1.1) } == 0 +} + +/// Token-endpoint transport, abstracted for checks. +public protocol AuthTransport: Sendable { + func post(_ url: URL, form: [String: String]) async throws -> Data +} + +public struct URLSessionAuthTransport: AuthTransport { + public init() {} + public func post(_ url: URL, form: [String: String]) async throws -> Data { + var req = URLRequest(url: url) + req.httpMethod = "POST" + req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + req.setValue("application/json", forHTTPHeaderField: "Accept") + var c = URLComponents(); c.queryItems = form.map { URLQueryItem(name: $0.key, value: $0.value) } + req.httpBody = Data((c.percentEncodedQuery ?? "").utf8) + let (data, resp) = try await URLSession.shared.data(for: req) + guard let http = resp as? HTTPURLResponse else { throw AuthError.network("no response") } + guard (200..<300).contains(http.statusCode) else { + if http.statusCode == 400 || http.statusCode == 401 { throw AuthError.expired } + throw AuthError.network("HTTP \(http.statusCode)") + } + return data + } +} + +public final class AuthService: @unchecked Sendable { + public let config: AuthConfiguration + private let secrets: SecretStore + private let transport: AuthTransport + + public init(config: AuthConfiguration, secrets: SecretStore, transport: AuthTransport = URLSessionAuthTransport()) { + self.config = config; self.secrets = secrets; self.transport = transport + } + + public func makeRequest(for provider: AuthProvider) throws -> AuthorizationRequest { + guard let broker = config.brokerURL else { throw AuthError.notConfigured } + let pkce = PKCE.generate(), state = PKCE.randomToken(bytes: 24) + var c = URLComponents(url: broker.appendingPathComponent("oauth/\(provider.rawValue)/authorize"), resolvingAgainstBaseURL: false)! + c.queryItems = [ + .init(name: "response_type", value: "code"), .init(name: "client_id", value: config.clientID), + .init(name: "redirect_uri", value: config.redirectURI), .init(name: "code_challenge", value: pkce.challenge), + .init(name: "code_challenge_method", value: PKCE.method), .init(name: "state", value: state), + .init(name: "scope", value: "openid email profile"), + ] + return AuthorizationRequest(provider: provider, pkce: pkce, state: state, url: c.url!) + } + + struct TokenResponse: Decodable { + let access_token: String + let refresh_token: String? + let expires_in: Double + let user: UserDTO? + let plan: String? + struct UserDTO: Decodable { let id: String; let name: String; let email: String?; let avatar_url: String? } + } + + public func complete(_ request: AuthorizationRequest, callback: URL) async throws -> AuthenticationSession { + let code = try request.code(from: callback) + let data = try await transport.post(tokenURL(), form: [ + "grant_type": "authorization_code", "code": code, "code_verifier": request.pkce.verifier, + "redirect_uri": config.redirectURI, "client_id": config.clientID, + ]) + let session = try makeSession(data, provider: request.provider, previous: nil) + try persist(session) + return session + } + + /// Restores the saved session, refreshing it if it has expired. + public func restore() async throws -> AuthenticationSession? { + guard let raw = try secrets.get(SecretAccount.authSession), + let s = try? JSONDecoder().decode(AuthenticationSession.self, from: Data(raw.utf8)) else { return nil } + if s.user.provider == .local || !s.isExpired { return s } + return try await refresh(s) + } + + public func refresh(_ s: AuthenticationSession) async throws -> AuthenticationSession { + guard let rt = s.refreshToken else { try signOut(); throw AuthError.expired } + do { + let data = try await transport.post(tokenURL(), form: ["grant_type": "refresh_token", "refresh_token": rt, "client_id": config.clientID]) + let ns = try makeSession(data, provider: s.user.provider, previous: s) + try persist(ns) + return ns + } catch AuthError.expired { + try signOut(); throw AuthError.expired + } + } + + /// A local-only profile for builds without a configured broker. Nothing is + /// sent anywhere; Pro features stay unavailable. + public func continueLocally(name: String) throws -> AuthenticationSession { + let s = AuthenticationSession(user: User(id: "local", name: name, email: nil, avatarURL: nil, provider: .local), + accessToken: "", refreshToken: nil, expiresAt: .distantFuture, subscription: .init()) + try persist(s) + return s + } + + public func signOut() throws { try secrets.delete(SecretAccount.authSession) } + + private func tokenURL() throws -> URL { + guard let b = config.brokerURL else { throw AuthError.notConfigured } + return b.appendingPathComponent("oauth/token") + } + + private func makeSession(_ data: Data, provider: AuthProvider, previous: AuthenticationSession?) throws -> AuthenticationSession { + let t = try JSONDecoder().decode(TokenResponse.self, from: data) + let user = t.user.map { User(id: $0.id, name: $0.name, email: $0.email, avatarURL: $0.avatar_url.flatMap(URL.init), provider: provider) } + ?? previous?.user ?? User(id: "unknown", name: "PGBot user", email: nil, avatarURL: nil, provider: provider) + var sub = previous?.subscription ?? Subscription() + if let p = t.plan, let plan = SubscriptionPlan(rawValue: p) { sub.plan = plan } + return AuthenticationSession(user: user, accessToken: t.access_token, refreshToken: t.refresh_token ?? previous?.refreshToken, + expiresAt: Date().addingTimeInterval(t.expires_in), subscription: sub) + } + + private func persist(_ s: AuthenticationSession) throws { + try secrets.set(String(decoding: try JSONEncoder().encode(s), as: UTF8.self), for: SecretAccount.authSession) + } +} diff --git a/desktop/macos/Sources/PGBotKit/Demo/DemoData.swift b/desktop/macos/Sources/PGBotKit/Demo/DemoData.swift new file mode 100644 index 0000000..fa67307 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Demo/DemoData.swift @@ -0,0 +1,216 @@ +import Foundation + +/// Explicitly labeled sample data for screenshots and demos. Every demo bot has +/// `isDemo = true`, the UI badges it "Demo", and the engine is never invoked for +/// it. The contexts below are hand-written in the engine's own JSON shape so they +/// exercise exactly the same decoding and rendering paths as real inspections. +public enum DemoData { + public struct Bundle { + public var bots: [DatabaseBot] + public var records: [InspectionRecord] + public var messages: [ChatMessage] + public var notifications: [AppNotification] + public var samples: [MetricSample] + public var logs: [UUID: [LogEntry]] + } + + struct Spec { + let name: String, color: BotColor, env: DatabaseEnvironment, host: String, db: String + let pinned: Bool, findings: [(String, String, Severity, String, String, String?)] + let conns: Int, size: Int64, tps: Double + } + + static let specs: [Spec] = [ + Spec(name: "Remotely Production", color: .blue, env: .production, host: "db.remotely.example", db: "remotely", + pinned: true, findings: [ + ("unused_indexes", "public.orders", .warn, "Three potentially unused indexes occupy 4.2 GB", + "orders_created_idx, orders_status_idx and orders_legacy_ref_idx have recorded 0 scans since statistics were reset 41 days ago.", + "Review their usage on every replica before considering removal."), + ("query_regression", "q:-81233409", .warn, "A query on orders became 2.3× slower than the previous baseline", + "Mean execution time rose from 38 ms to 87 ms across 18.4k calls since yesterday's baseline.", + "Run “Explain SQL” on the query to see whether the plan changed."), + ], conns: 42, size: 26_628_797_235, tps: 812), + Spec(name: "PGBox", color: .green, env: .production, host: "pgbox.internal", db: "pgbox", + pinned: true, findings: [], conns: 18, size: 3_400_000_000, tps: 120), + Spec(name: "Ekomspace", color: .orange, env: .production, host: "ekom.example.net", db: "ekom", + pinned: true, findings: [ + ("autovacuum_behind", "public.events", .warn, "Autovacuum is behind on public.events", + "public.events has 31% dead tuples (4.1M) and was last vacuumed 3 days ago.", + "Lower autovacuum_vacuum_scale_factor for this table."), + ], conns: 63, size: 9_900_000_000, tps: 340), + Spec(name: "Local Postgres", color: .black, env: .local, host: "localhost", db: "app_dev", + pinned: false, findings: [], conns: 4, size: 180_000_000, tps: 3), + Spec(name: "Staging", color: .black, env: .staging, host: "staging-db.example.net", db: "app", + pinned: false, findings: [], conns: 9, size: 2_100_000_000, tps: 14), + ] + + public static func make(now: Date = Date()) -> Bundle { + var bots: [DatabaseBot] = [], records: [InspectionRecord] = [], messages: [ChatMessage] = [] + var notes: [AppNotification] = [], samples: [MetricSample] = [], logs: [UUID: [LogEntry]] = [:] + for (i, s) in specs.enumerated() { + let id = UUID(uuidString: String(format: "D3E00000-0000-4000-8000-%012d", i + 1))! + let ctx = try! EngineJSON.decodeContext(contextJSON(s, at: now)) + let rec = InspectionRecord(botID: id, startedAt: now.addingTimeInterval(-8), finishedAt: now, context: ctx) + var bot = DatabaseBot(id: id, displayName: s.name, description: "Sample database (demo)", + avatar: BotAvatar(color: s.color, shape: i == 1 ? .roundedSquare : .circle), environment: s.env, + connection: DatabaseConnection(host: s.host, database: s.db, username: "pgbot_ro", sslMode: .require), + pinned: s.pinned, sortOrder: i, isDemo: true, + status: s.findings.isEmpty ? .healthy : .degraded, lastInspectedAt: now.addingTimeInterval(-300)) + bot.lastScore = rec.score.value + bot.lastSummary = i == 0 ? "2 new findings · Query regression" + : (s.findings.isEmpty ? "Healthy · " + (s.env == .local ? "Development" : "No new findings") + : "1 warning · Autovacuum is behind") + bot.unreadCount = i == 0 ? 2 : (s.findings.isEmpty ? 0 : 1) + bots.append(bot); records.append(rec) + samples += history(botID: id, base: s, score: rec.score.value, now: now) + logs[id] = demoLogs(now: now) + } + + // A day in the life of the hero bot. + let hero = bots[0], cal = Calendar.current + func today(_ h: Int, _ m: Int) -> Date { cal.date(bySettingHour: h, minute: m, second: 0, of: now) ?? now } + let r0 = records[0] + messages.append(ReportComposer.healthReport(bot: hero, record: r0, previous: nil, firstRun: true, scheduled: false) + .with(createdAt: today(8, 2))) + var morning = ReportComposer.healthReport(bot: hero, record: r0, previous: nil, firstRun: false, scheduled: true) + morning.createdAt = today(9, 0) + messages.append(morning) + let q = ChatMessage(botID: hero.id, role: .user, payload: .text("Why is the orders query slower?"), createdAt: today(10, 26)) + messages.append(q) + messages.append(ChatMessage(botID: hero.id, role: .assistant, payload: .text(""" + The slowdown is in one statement: the `orders` lookup by `customer_id` and `status` (queryid -81233409). \ + Its mean time rose from **38 ms to 87 ms** across 18.4k calls since yesterday's baseline, while the call rate stayed flat — \ + so this is per-call cost, not load. + + What the evidence supports: + - Shared-buffer reads for that query rose sharply, consistent with a plan that touches more pages. + - No configuration change or stats reset was recorded in the window. + + What it doesn't show: whether the plan itself changed. pgbot doesn't keep historical plans, so I can't confirm that. + + **Next step:** run *Explain SQL* on the query to see its current plan. + """), createdAt: today(10, 27), inReplyTo: q.id, modelName: "demo")) + messages.append(ChatMessage(botID: hero.id, role: .assistant, payload: .resolved([ + Finding(id: "connections_high", severity: .warn, title: "Connection usage returned to normal levels", detail: "") + ]), createdAt: today(12, 45))) + for b in bots.dropFirst() { + let r = records.first { $0.botID == b.id }! + messages.append(ReportComposer.healthReport(bot: b, record: r, previous: nil, firstRun: true, scheduled: false)) + } + + notes = [ + AppNotification(botID: hero.id, category: .regression, severity: .warn, title: "Remotely Production — Warning", + body: "A query on orders became 2.3× slower", createdAt: today(10, 24), dedupKey: "demo1"), + AppNotification(botID: hero.id, category: .warning, severity: .warn, title: "Remotely Production — Warning", + body: "Three potentially unused indexes occupy 4.2 GB", createdAt: today(11, 15), dedupKey: "demo2"), + AppNotification(botID: bots[2].id, category: .warning, severity: .warn, title: "Ekomspace — Warning", + body: "Autovacuum is behind on public.events", createdAt: today(7, 40), dedupKey: "demo3"), + AppNotification(botID: hero.id, category: .resolved, severity: .info, title: "Remotely Production — resolved", + body: "Connection usage returned to normal levels", createdAt: today(12, 45), read: true, dedupKey: "demo4"), + AppNotification(botID: bots[1].id, category: .scheduledReport, severity: .info, title: "PGBox — daily report", + body: "Healthy. No warnings or critical findings.", createdAt: today(9, 0), read: true, dedupKey: "demo5"), + ] + return Bundle(bots: bots, records: records, messages: messages, notifications: notes, samples: samples, logs: logs) + } + + static func history(botID: UUID, base: Spec, score: Int, now: Date) -> [MetricSample] { + var out: [MetricSample] = [] + var rng = SeededRNG(seed: UInt64(base.conns * 7919)) + let hours = 24 * 30 + for h in stride(from: hours, through: 0, by: -1) { + let at = now.addingTimeInterval(Double(-h) * 3600) + let hour = Double(Calendar.current.component(.hour, from: at)) + let diurnal = 0.65 + 0.35 * sin((hour - 8) / 24 * 2 * .pi) + func jitter(_ x: Double) -> Double { x * (0.92 + 0.16 * Double.random(in: 0...1, using: &rng)) } + let growth = 1 - Double(h) / Double(hours) * 0.06 + out += [ + .init(botID: botID, metric: .connections, at: at, value: (jitter(Double(base.conns) * diurnal)).rounded()), + .init(botID: botID, metric: .connectionUtilization, at: at, value: jitter(Double(base.conns) * diurnal) / 100), + .init(botID: botID, metric: .tps, at: at, value: jitter(base.tps * diurnal)), + .init(botID: botID, metric: .cacheHitRatio, at: at, value: min(0.9999, 0.990 + 0.004 * Double.random(in: 0...1, using: &rng))), + .init(botID: botID, metric: .dbSizeBytes, at: at, value: Double(base.size) * growth), + .init(botID: botID, metric: .walBytesPerSec, at: at, value: jitter(base.tps * 2100 * diurnal)), + .init(botID: botID, metric: .replicationLagSec, at: at, value: jitter(0.012)), + .init(botID: botID, metric: .healthScore, at: at, value: Double(h < 30 ? score : min(100, score + 3))), + .init(botID: botID, metric: .deadlocksPerMin, at: at, value: h % 97 == 0 ? 1 : 0), + .init(botID: botID, metric: .activeSessions, at: at, value: (jitter(Double(base.conns) * 0.2 * diurnal)).rounded()), + ] + } + return out + } + + static func demoLogs(now: Date) -> [LogEntry] { + let rows: [(Double, String, String, String, String?)] = [ + (-60, "LOG", "info", "checkpoint complete: wrote 1832 buffers (11.2%); 0 WAL file(s) added", nil), + (-240, "ERROR", "error", "deadlock detected", "Process 48211 waits for ShareLock on transaction 99812; blocked by process 48190."), + (-600, "WARNING", "warn", "there is already a transaction in progress", nil), + (-900, "ERROR", "error", "canceling statement due to statement timeout", "STATEMENT: SELECT … FROM orders WHERE customer_id = $1"), + (-1500, "FATAL", "error", "password authentication failed for user \"report_ro\"", nil), + (-2400, "LOG", "info", "automatic vacuum of table \"remotely.public.events\": index scans: 1", nil), + (-3600, "LOG", "query", "duration: 2412.118 ms statement: SELECT … FROM orders o JOIN customers c …", nil), + ] + return rows.map { LogEntry(time: now.addingTimeInterval($0.0), severity: $0.1, level: $0.2, message: $0.3, detail: $0.4, + user: "app", database: "remotely", pid: 48000 + Int(-$0.0) % 900, app: "api") } + } + + static func contextJSON(_ s: Spec, at: Date) -> Data { + let ts = ISO8601DateFormatter().string(from: at) + let findings = s.findings.map { f in + """ + {"id":"\(f.0)","object":"\(f.1)","severity":"\(f.2.rawValue)","title":"\(f.3)","detail":"\(f.4)", + "remediation":\(f.5.map { "\"\($0)\"" } ?? "null"), + "impact":{"score":70,"dimension":"\(f.0 == "query_regression" ? "latency" : "storage")","estimate":"","basis":"demo"}, + "confidence":0.8} + """ + }.joined(separator: ",") + let unused = s.findings.contains { $0.0 == "unused_indexes" } ? """ + [{"schema":"public","table":"orders","index":"orders_created_idx","scans":0,"bytes":1932735283}, + {"schema":"public","table":"orders","index":"orders_status_idx","scans":0,"bytes":1395864371}, + {"schema":"public","table":"orders","index":"orders_legacy_ref_idx","scans":0,"bytes":1181116006}] + """ : "[]" + let json = """ + {"schema_version":"1.6.0","collected_at":"\(ts)","fingerprint":"demo-\(s.db)", + "server":{"version_num":160004,"version_text":"PostgreSQL 16.4","database":"\(s.db)","uptime_seconds":3888000, + "extensions":["pg_stat_statements"],"capabilities":["pg_stat_statements"],"has_pg_monitor":true}, + "window":{"sample_seconds":3}, + "health":{"exactness":"sampled","connections":\(s.conns),"tps":\(s.tps),"rollback_ratio":0.002,"cache_hit_ratio":0.994,"deadlocks_per_min":0}, + "activity":{"exactness":"scraped","total":\(s.conns),"active":\(max(1, s.conns / 5)),"idle":\(s.conns - s.conns / 5 - 1),"idle_in_transaction":1,"waiting":0, + "by_state":{},"longest_xact_sec":4.2,"longest_active_sec":1.1}, + "locks":{"exactness":"scraped","blocked_count":0}, + "queries":{"exactness":"cumulative","enabled":true,"total_exec_ms":91234567,"top":[ + {"queryid":-81233409,"query":"SELECT o.* FROM orders o WHERE o.customer_id = $1 AND o.status = $2 ORDER BY o.created_at DESC LIMIT $3","calls":18400,"total_ms":1600800,"mean_ms":87,"max_ms":2412,"rows":184000,"cache_hit":0.93,"wal_bytes":0}, + {"queryid":5512,"query":"UPDATE carts SET updated_at = now() WHERE id = $1","calls":912000,"total_ms":820800,"mean_ms":0.9,"max_ms":41,"rows":912000,"cache_hit":0.999,"wal_bytes":81234567}, + {"queryid":7731,"query":"INSERT INTO events (kind, payload, created_at) VALUES ($1, $2, $3)","calls":2400000,"total_ms":480000,"mean_ms":0.2,"max_ms":12,"rows":2400000,"cache_hit":0.998,"wal_bytes":912345678}, + {"queryid":9001,"query":"SELECT count(*) FROM sessions WHERE expires_at > now()","calls":1440,"total_ms":201600,"mean_ms":140,"max_ms":390,"rows":1440,"cache_hit":0.97,"wal_bytes":0}]}, + "tables":{"exactness":"scraped","db_size_bytes":\(s.size),"top":[ + {"schema":"public","table":"orders","total_bytes":\(s.size / 3),"live_tuples":48000000,"dead_tuples":900000,"dead_ratio":0.018,"seq_scans":12,"index_scans":9812345}, + {"schema":"public","table":"events","total_bytes":\(s.size / 4),"live_tuples":132000000,"dead_tuples":4100000,"dead_ratio":0.031,"seq_scans":3,"index_scans":120344}, + {"schema":"public","table":"customers","total_bytes":\(s.size / 12),"live_tuples":2100000,"dead_tuples":2100,"dead_ratio":0.001,"seq_scans":40,"index_scans":4412345}]}, + "indexes":{"exactness":"cumulative","total":48,"unused":\(unused)}, + "wal":{"exactness":"sampled","bytes_per_sec":\(s.tps * 2100)}, + "replication":{"exactness":"scraped","is_replica":false,"replicas":[{"client_addr":"10.0.4.12","application_name":"replica-1","state":"streaming","sync_state":"async","replay_lag_sec":0.012,"replay_lag_bytes":8192,"write_lag_bytes":0,"flush_lag_bytes":0}], + "slots":[{"name":"replica_1","type":"physical","active":true,"retained_bytes":16777216}]}, + "limits":{"connections_used":\(s.conns),"connections_max":100,"max_xid_age":184000000}, + "findings":[\(findings)]} + """ + return Data(json.utf8) + } +} + +extension ChatMessage { + func with(createdAt: Date) -> ChatMessage { var c = self; c.createdAt = createdAt; return c } +} + +/// Deterministic randomness so demo charts are stable across launches. +struct SeededRNG: RandomNumberGenerator { + var state: UInt64 + init(seed: UInt64) { state = seed == 0 ? 0x9E3779B97F4A7C15 : seed } + mutating func next() -> UInt64 { + state ^= state << 13; state ^= state >> 7; state ^= state << 17; return state + } +} + +public extension DemoData { + /// The hero demo context in engine JSON form, for contract checks. + static func contextJSONForChecks() -> Data { contextJSON(specs[0], at: Date()) } +} diff --git a/desktop/macos/Sources/PGBotKit/Engine/AIProvider.swift b/desktop/macos/Sources/PGBotKit/Engine/AIProvider.swift new file mode 100644 index 0000000..8399717 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Engine/AIProvider.swift @@ -0,0 +1,76 @@ +import Foundation + +/// AI providers the engine's `internal/ai` already speaks. The app only chooses +/// and configures one; every model call is made by the engine (`pgbot ask`, +/// `pgbot sql explain --ai`), grounded on deterministic findings. +public enum AIProviderKind: String, Codable, Sendable, CaseIterable, Identifiable { + case anthropic, openai, gemini, xai, openaiCompatible, ollama + public var id: String { rawValue } + + public var label: String { + switch self { + case .anthropic: "Anthropic Claude" + case .openai: "OpenAI" + case .gemini: "Google Gemini" + case .xai: "xAI Grok" + case .openaiCompatible: "OpenAI-compatible endpoint" + case .ollama: "Ollama (local)" + } + } + + /// PGBOT_AI_PROVIDER value (internal/ai/resolve.go). + public var engineName: String { + switch self { + case .anthropic: "anthropic" + case .openai: "openai" + case .gemini: "gemini" + case .xai: "xai" + case .openaiCompatible: "openai-compatible" + case .ollama: "ollama" + } + } + + public var needsKey: Bool { self != .ollama } + public var needsBaseURL: Bool { self == .openaiCompatible } + public var defaultBaseURL: String? { self == .ollama ? "http://localhost:11434/v1" : nil } + public var suggestedModels: [String] { + switch self { + case .anthropic: ["claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"] + case .openai: ["gpt-5", "gpt-5-mini"] + case .gemini: ["gemini-2.5-pro", "gemini-2.5-flash"] + case .xai: ["grok-4"] + case .openaiCompatible: [] + case .ollama: ["llama3.1", "qwen2.5"] + } + } +} + +public struct AIConfiguration: Codable, Sendable, Equatable { + public var provider: AIProviderKind + public var model: String + public var baseURL: String + public init(provider: AIProviderKind = .anthropic, model: String = "", baseURL: String = "") { + self.provider = provider; self.model = model; self.baseURL = baseURL + } + + public var effectiveBaseURL: String? { + let b = baseURL.trimmingCharacters(in: .whitespaces) + return b.isEmpty ? provider.defaultBaseURL : b + } + + /// True when the request never leaves this Mac — matches ai.Local's notion + /// closely enough to choose consent wording (the engine re-checks). + public var isLocal: Bool { + guard let b = effectiveBaseURL, let host = URL(string: b)?.host?.lowercased() else { return false } + return host == "localhost" || host == "127.0.0.1" || host == "::1" || host.hasSuffix(".local") + } + + /// Environment for the engine. The key is passed only here, in-process, from the Keychain. + public func environment(apiKey: String?) -> [String: String] { + var env = ["PGBOT_AI_PROVIDER": provider.engineName] + if let k = apiKey, !k.isEmpty { env["PGBOT_AI_API_KEY"] = k } + if !model.trimmingCharacters(in: .whitespaces).isEmpty { env["PGBOT_AI_MODEL"] = model } + if let b = effectiveBaseURL { env["PGBOT_AI_BASE_URL"] = b } + return env + } +} diff --git a/desktop/macos/Sources/PGBotKit/Engine/EngineContext.swift b/desktop/macos/Sources/PGBotKit/Engine/EngineContext.swift new file mode 100644 index 0000000..d017053 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Engine/EngineContext.swift @@ -0,0 +1,523 @@ +import Foundation + +// A read-only Swift mirror of the subset of pgbot's versioned Context contract +// (internal/model/context.go, schema/pgbot-context-*.json) that the desktop app +// renders. The contract is additive-only, so unknown keys are ignored and every +// optional section stays optional: a missing section means "not collected", and +// a section whose `exactness` is "unavailable" means "could not be collected". +// Nothing here is computed by the app — these are the engine's numbers. + +public struct EngineContext: Codable, Sendable, Equatable { + public var schemaVersion: String + public var collectedAt: Date + public var fingerprint: String + public var server: ServerInfo + public var window: Window? + public var health: HealthSection? + public var activity: ActivitySection? + public var locks: LocksSection? + public var queries: QueriesSection? + public var tables: TablesSection? + public var indexes: IndexesSection? + public var wal: WALSection? + public var replication: ReplicationSection? + public var settings: SettingsSection? + public var limits: Limits? + public var deltas: Deltas? + public var deltaSuppressedReason: String? + public var events: [Event]? + public var waitProfile: WaitProfile? + public var findings: [Finding] + public var configWarnings: [String]? + + enum CodingKeys: String, CodingKey { + case schemaVersion = "schema_version", collectedAt = "collected_at", fingerprint, server, window + case health, activity, locks, queries, tables, indexes, wal, replication, settings, limits, deltas + case deltaSuppressedReason = "delta_suppressed_reason", events, waitProfile = "wait_profile" + case findings, configWarnings = "config_warnings" + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + schemaVersion = try c.decode(String.self, forKey: .schemaVersion) + collectedAt = try c.decode(Date.self, forKey: .collectedAt) + fingerprint = try c.decodeIfPresent(String.self, forKey: .fingerprint) ?? "" + server = try c.decode(ServerInfo.self, forKey: .server) + window = try c.decodeIfPresent(Window.self, forKey: .window) + health = try c.decodeIfPresent(HealthSection.self, forKey: .health) + activity = try c.decodeIfPresent(ActivitySection.self, forKey: .activity) + locks = try c.decodeIfPresent(LocksSection.self, forKey: .locks) + queries = try c.decodeIfPresent(QueriesSection.self, forKey: .queries) + tables = try c.decodeIfPresent(TablesSection.self, forKey: .tables) + indexes = try c.decodeIfPresent(IndexesSection.self, forKey: .indexes) + wal = try c.decodeIfPresent(WALSection.self, forKey: .wal) + replication = try c.decodeIfPresent(ReplicationSection.self, forKey: .replication) + settings = try c.decodeIfPresent(SettingsSection.self, forKey: .settings) + limits = try c.decodeIfPresent(Limits.self, forKey: .limits) + deltas = try c.decodeIfPresent(Deltas.self, forKey: .deltas) + deltaSuppressedReason = try c.decodeIfPresent(String.self, forKey: .deltaSuppressedReason) + events = try c.decodeIfPresent([Event].self, forKey: .events) + waitProfile = try c.decodeIfPresent(WaitProfile.self, forKey: .waitProfile) + // `findings` is always emitted, but as `null` when empty in some paths. + findings = try c.decodeIfPresent([Finding].self, forKey: .findings) ?? [] + configWarnings = try c.decodeIfPresent([String].self, forKey: .configWarnings) + } + + /// The major.minor of the contract, for compatibility checks. + public var schemaMajor: Int { Int(schemaVersion.split(separator: ".").first ?? "0") ?? 0 } +} + +public enum Exactness: String, Codable, Sendable { + case sampled, cumulative, scraped, unavailable + case unknown + public init(from decoder: Decoder) throws { + let raw = try decoder.singleValueContainer().decode(String.self) + self = Exactness(rawValue: raw) ?? .unknown + } +} + +/// Every engine section carries its exactness and, when unavailable, why. +public protocol EngineSection { + var exactness: Exactness? { get } + var reason: String? { get } +} + +public extension EngineSection { + var isAvailable: Bool { exactness != .unavailable } +} + +public struct ServerInfo: Codable, Sendable, Equatable { + public var versionNum: Int + public var versionText: String + public var database: String + public var provider: String? + public var inRecovery: Bool? + public var viaPooler: Bool? + public var uptimeSeconds: Int64? + public var extensions: [String]? + public var capabilities: [String]? + public var hasPgMonitor: Bool? + + enum CodingKeys: String, CodingKey { + case versionNum = "version_num", versionText = "version_text", database, provider + case inRecovery = "in_recovery", viaPooler = "via_pooler", uptimeSeconds = "uptime_seconds" + case extensions, capabilities, hasPgMonitor = "has_pg_monitor" + } + + /// "PostgreSQL 16.3" from version_num 160003. + public var displayVersion: String { + guard versionNum > 0 else { return "PostgreSQL" } + let major = versionNum / 10000, minor = versionNum % 100 + return "PostgreSQL \(major).\(minor)" + } +} + +public struct Window: Codable, Sendable, Equatable { + public var sampleSeconds: Double? + public var statsResetAt: Date? + public var windowAgeSeconds: Int64? + enum CodingKeys: String, CodingKey { + case sampleSeconds = "sample_seconds", statsResetAt = "stats_reset_at", windowAgeSeconds = "window_age_seconds" + } +} + +public struct HealthSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var connections: Int? + public var tps: Double? + public var commitsPerSec: Double? + public var rollbacksPerSec: Double? + public var rollbackRatio: Double? + public var cacheHitRatio: Double? + public var deadlocksPerMin: Double? + public var tempBytesPerSec: Double? + public var tuplesReturnedPerSec: Double? + public var tuplesWrittenPerSec: Double? + enum CodingKeys: String, CodingKey { + case exactness, reason, connections, tps, commitsPerSec = "commits_per_sec" + case rollbacksPerSec = "rollbacks_per_sec", rollbackRatio = "rollback_ratio" + case cacheHitRatio = "cache_hit_ratio", deadlocksPerMin = "deadlocks_per_min" + case tempBytesPerSec = "temp_bytes_per_sec", tuplesReturnedPerSec = "tuples_returned_per_sec" + case tuplesWrittenPerSec = "tuples_written_per_sec" + } +} + +public struct ConnGroup: Codable, Sendable, Equatable, Hashable { + public var appName: String + public var user: String + public var state: String + public var count: Int + enum CodingKeys: String, CodingKey { case appName = "app_name", user, state, count } +} + +public struct ActivitySection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var total: Int? + public var active: Int? + public var idle: Int? + public var idleInTransaction: Int? + public var waiting: Int? + public var waitEvents: [String: Int]? + public var longestXactSec: Double? + public var longestIdleXactSec: Double? + public var longestActiveSec: Double? + public var connections: [ConnGroup]? + public var autovacuumWorkers: Int? + enum CodingKeys: String, CodingKey { + case exactness, reason, total, active, idle, idleInTransaction = "idle_in_transaction", waiting + case waitEvents = "wait_events", longestXactSec = "longest_xact_sec" + case longestIdleXactSec = "longest_idle_xact_sec", longestActiveSec = "longest_active_sec" + case connections, autovacuumWorkers = "autovacuum_workers" + } +} + +public struct BlockingRow: Codable, Sendable, Equatable, Hashable { + public var blockedPID: Int + public var blockingPIDs: [Int64] + public var waitEvent: String? + public var waitSeconds: Double + public var blockedQuery: String + enum CodingKeys: String, CodingKey { + case blockedPID = "blocked_pid", blockingPIDs = "blocking_pids", waitEvent = "wait_event" + case waitSeconds = "wait_seconds", blockedQuery = "blocked_query" + } +} + +public struct LocksSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var blockedCount: Int? + public var chains: [BlockingRow]? + enum CodingKeys: String, CodingKey { case exactness, reason, blockedCount = "blocked_count", chains } +} + +public struct QueryStat: Codable, Sendable, Equatable, Hashable, Identifiable { + public var queryID: Int64 + public var query: String + public var calls: Int64 + public var totalMS: Double + public var meanMS: Double + public var maxMS: Double? + public var rows: Int64? + public var cacheHit: Double? + public var walBytes: Int64? + public var id: Int64 { queryID } + enum CodingKeys: String, CodingKey { + case queryID = "queryid", query, calls, totalMS = "total_ms", meanMS = "mean_ms", maxMS = "max_ms" + case rows, cacheHit = "cache_hit", walBytes = "wal_bytes" + } +} + +public struct QueriesSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var enabled: Bool? + public var totalExecMS: Double? + public var top: [QueryStat]? + enum CodingKeys: String, CodingKey { case exactness, reason, enabled, totalExecMS = "total_exec_ms", top } +} + +public struct TableStat: Codable, Sendable, Equatable, Hashable, Identifiable { + public var schema: String + public var name: String + public var totalBytes: Int64 + public var liveTuples: Int64 + public var deadTuples: Int64 + public var deadRatio: Double + public var seqScans: Int64? + public var indexScans: Int64? + public var lastVacuum: Date? + public var lastAutovacuum: Date? + public var lastAnalyze: Date? + public var lastAutoanalyze: Date? + public var autovacuumDisabled: Bool? + public var id: String { schema + "." + name } + enum CodingKeys: String, CodingKey { + case schema, name = "table", totalBytes = "total_bytes", liveTuples = "live_tuples" + case deadTuples = "dead_tuples", deadRatio = "dead_ratio", seqScans = "seq_scans", indexScans = "index_scans" + case lastVacuum = "last_vacuum", lastAutovacuum = "last_autovacuum", lastAnalyze = "last_analyze" + case lastAutoanalyze = "last_autoanalyze", autovacuumDisabled = "autovacuum_disabled" + } + public var lastAnyVacuum: Date? { [lastVacuum, lastAutovacuum].compactMap { $0 }.max() } +} + +public struct TablesSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var dbSizeBytes: Int64? + public var top: [TableStat]? + enum CodingKeys: String, CodingKey { case exactness, reason, dbSizeBytes = "db_size_bytes", top } +} + +public struct IndexStat: Codable, Sendable, Equatable, Hashable, Identifiable { + public var schema: String + public var table: String + public var name: String + public var scans: Int64 + public var bytes: Int64 + public var definition: String? + public var unique: Bool? + public var primary: Bool? + public var id: String { schema + "." + name } + enum CodingKeys: String, CodingKey { case schema, table, name = "index", scans, bytes, definition, unique, primary } +} + +public struct IndexesSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var total: Int? + public var unused: [IndexStat]? + public var largest: [IndexStat]? +} + +public struct WALSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var bytesPerSec: Double? + public var dirBytes: Int64? + enum CodingKeys: String, CodingKey { case exactness, reason, bytesPerSec = "bytes_per_sec", dirBytes = "dir_bytes" } +} + +public struct ReplicaRow: Codable, Sendable, Equatable, Hashable { + public var clientAddr: String + public var appName: String? + public var state: String + public var syncState: String + public var replayLagSec: Double? + public var replayLagBytes: Int64? + enum CodingKeys: String, CodingKey { + case clientAddr = "client_addr", appName = "application_name", state, syncState = "sync_state" + case replayLagSec = "replay_lag_sec", replayLagBytes = "replay_lag_bytes" + } +} + +public struct ReplicationSlot: Codable, Sendable, Equatable, Hashable { + public var name: String + public var type: String + public var active: Bool + public var retainedBytes: Int64 + public var walStatus: String? + enum CodingKeys: String, CodingKey { case name, type, active, retainedBytes = "retained_bytes", walStatus = "wal_status" } +} + +public struct ReplicationSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var isReplica: Bool? + public var replicas: [ReplicaRow]? + public var receiverLagSec: Double? + public var slots: [ReplicationSlot]? + enum CodingKeys: String, CodingKey { + case exactness, reason, isReplica = "is_replica", replicas, receiverLagSec = "receiver_lag_sec", slots + } +} + +public struct SettingsSection: Codable, Sendable, Equatable, EngineSection { + public var exactness: Exactness? + public var reason: String? + public var overrides: [String: String]? + public var params: [String: String]? +} + +public struct Limits: Codable, Sendable, Equatable { + public var connectionsUsed: Int + public var connectionsMax: Int + public var maxXIDAge: Int64? + enum CodingKeys: String, CodingKey { case connectionsUsed = "connections_used", connectionsMax = "connections_max", maxXIDAge = "max_xid_age" } + public var utilization: Double? { connectionsMax > 0 ? Double(connectionsUsed) / Double(connectionsMax) : nil } + /// Fraction of the ~2^31 transaction-ID wraparound wall consumed. + public var wraparoundFraction: Double? { maxXIDAge.map { Double($0) / 2_147_483_648.0 } } +} + +public struct Delta: Codable, Sendable, Equatable, Hashable { + public var id: String + public var subject: String + public var severity: String + public var before: Double + public var after: Double + public var pctChange: Double? + public var note: String? + enum CodingKeys: String, CodingKey { case id, subject, severity, before, after, pctChange = "pct_change", note } +} + +public struct Deltas: Codable, Sendable, Equatable { + public var against: Date + public var changes: [Delta]? +} + +public struct Event: Codable, Sendable, Equatable, Hashable { + public var kind: String + public var object: String? + public var before: String? + public var after: String? + public var confidence: Double? +} + +public struct WaitBucket: Codable, Sendable, Equatable, Hashable { + public var type: String + public var count: Int + public var share: Double +} + +public struct WaitProfile: Codable, Sendable, Equatable { + public var available: Bool + public var reason: String? + public var samples: Int? + public var windowSeconds: Double? + public var buckets: [WaitBucket]? + enum CodingKeys: String, CodingKey { case available, reason, samples, windowSeconds = "window_seconds", buckets } +} + +public struct Impact: Codable, Sendable, Equatable, Hashable { + public var score: Double + public var dimension: String + public var estimate: String + public var basis: String +} + +public struct SafetyGuard: Codable, Sendable, Equatable, Hashable { + public var id: String + public var action: String + public var text: String + public var verify: String? +} + +public struct Safety: Codable, Sendable, Equatable, Hashable { + public var blockingCaveats: [SafetyGuard]? + enum CodingKeys: String, CodingKey { case blockingCaveats = "blocking_caveats" } +} + +public enum Severity: String, Codable, Sendable, Comparable, CaseIterable { + case info, warn, critical + public init(from decoder: Decoder) throws { + let raw = try decoder.singleValueContainer().decode(String.self) + self = Severity(rawValue: raw) ?? .info + } + public var rank: Int { switch self { case .info: 1; case .warn: 2; case .critical: 3 } } + public static func < (a: Severity, b: Severity) -> Bool { a.rank < b.rank } + public var label: String { switch self { case .info: "Info"; case .warn: "Warning"; case .critical: "Critical" } } +} + +public struct Finding: Codable, Sendable, Equatable, Hashable, Identifiable { + public var id: String + public var object: String? + public var severity: Severity + public var title: String + public var detail: String + public var evidence: [String]? + public var remediation: String? + public var impact: Impact? + public var confidence: Double? + public var caveats: [String]? + public var safety: Safety? + public var suppressed: Bool? + public var suppressionReason: String? + + enum CodingKeys: String, CodingKey { + case id, object, severity, title, detail, evidence, remediation, impact, confidence, caveats, safety + case suppressed, suppressionReason = "suppression_reason" + } + + public init(id: String, object: String? = nil, severity: Severity, title: String, detail: String, + evidence: [String]? = nil, remediation: String? = nil, impact: Impact? = nil, + confidence: Double? = nil, caveats: [String]? = nil, safety: Safety? = nil, + suppressed: Bool? = nil, suppressionReason: String? = nil) { + self.id = id; self.object = object; self.severity = severity; self.title = title; self.detail = detail + self.evidence = evidence; self.remediation = remediation; self.impact = impact; self.confidence = confidence + self.caveats = caveats; self.safety = safety; self.suppressed = suppressed; self.suppressionReason = suppressionReason + } + + /// Identity for diffing runs — the engine's own rule (monitor.FindingState.Key): + /// id + object, never the title (titles embed counts that change run to run). + public var key: String { object.map { "\(id)|\($0)" } ?? id } + public var isSuppressed: Bool { suppressed ?? false } + /// Below 0.5 the engine renders a finding as "possible", not an assertion. + public var isTentative: Bool { (confidence ?? 1) < 0.5 } +} + +// MARK: - Other engine JSON documents + +/// One `pgbot logs --json` entry (literals already scrubbed by the engine). +public struct LogEntry: Codable, Sendable, Equatable, Hashable, Identifiable { + public var time: Date + public var severity: String + public var level: String + public var message: String + public var detail: String? + public var user: String? + public var database: String? + public var pid: Int? + public var app: String? + public var id: String { "\(time.timeIntervalSince1970)-\(pid ?? 0)-\(message.hashValue)" } +} + +/// One `pgbot activity --json` session (query scrubbed by the engine). +public struct SessionRow: Codable, Sendable, Equatable, Hashable, Identifiable { + public var pid: Int + public var user: String? + public var db: String? + public var app: String? + public var state: String + public var wait: String? + public var xactAgeS: Double? + public var queryAgeS: Double? + public var query: String? + public var id: Int { pid } + enum CodingKeys: String, CodingKey { + case pid, user, db, app, state, wait, xactAgeS = "xact_age_s", queryAgeS = "query_age_s", query + } +} + +// MARK: - Decoding + +public enum EngineJSON { + /// Go's time.Time marshals as RFC 3339 with optional nanoseconds. + public static func decoder() -> JSONDecoder { + let d = JSONDecoder() + d.dateDecodingStrategy = .custom { dec in + let s = try dec.singleValueContainer().decode(String.self) + if let date = parseDate(s) { return date } + throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "bad date \(s)")) + } + return d + } + + public static func encoder() -> JSONEncoder { + let e = JSONEncoder() + e.dateEncodingStrategy = .custom { date, enc in + var c = enc.singleValueContainer() + try c.encode(fractional.string(from: date)) + } + return e + } + + nonisolated(unsafe) private static let fractional: ISO8601DateFormatter = { + let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]; return f + }() + nonisolated(unsafe) private static let plain: ISO8601DateFormatter = { + let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime]; return f + }() + + static func parseDate(_ s: String) -> Date? { + if let d = fractional.date(from: s) ?? plain.date(from: s) { return d } + // ISO8601DateFormatter accepts at most millisecond precision on some OS + // versions; Go emits nanoseconds. Trim the fraction to 3 digits and retry. + if let dot = s.firstIndex(of: "."), let tz = s[dot...].firstIndex(where: { $0 == "Z" || $0 == "+" || $0 == "-" }) { + let frac = s[s.index(after: dot).. EngineContext { + try decoder().decode(EngineContext.self, from: data) + } + + /// Parses newline-delimited JSON, skipping lines that are not objects of T. + public static func decodeLines(_ type: T.Type, from data: Data) -> [T] { + let d = decoder() + return data.split(separator: UInt8(ascii: "\n")).compactMap { try? d.decode(T.self, from: Data($0)) } + } +} diff --git a/desktop/macos/Sources/PGBotKit/Engine/EngineRunner.swift b/desktop/macos/Sources/PGBotKit/Engine/EngineRunner.swift new file mode 100644 index 0000000..cff08e9 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Engine/EngineRunner.swift @@ -0,0 +1,265 @@ +import Foundation + +/// Runs the bundled pgbot binary. +/// +/// Security invariants (each is asserted in EngineRunnerChecks): +/// * Credentials never appear in argv — the DSN goes in `PGBOT_DATABASE_URL`, +/// AI keys in `PGBOT_AI_API_KEY`, SQL over stdin. `ps` shows only flags. +/// * The child gets a minimal, allow-listed environment, not the app's: a stray +/// `DATABASE_URL` or `OPENAI_API_KEY` in the user's session can't redirect a +/// run or leak a key to a provider the user didn't choose. +/// * stderr is redacted before it reaches any UI, log, or error. +/// * Every run has a timeout, honors Task cancellation (SIGTERM, then SIGKILL), +/// and goes through a global concurrency limit. +public actor EngineRunner { + public struct Invocation: Sendable { + public var arguments: [String] + public var environment: [String: String] + public var stdin: Data? + public var timeout: Duration + /// Values to scrub from stderr in addition to the generic redaction. + public var secrets: [String] + public init(arguments: [String], environment: [String: String] = [:], stdin: Data? = nil, + timeout: Duration = .seconds(90), secrets: [String] = []) { + self.arguments = arguments; self.environment = environment; self.stdin = stdin + self.timeout = timeout; self.secrets = secrets + } + } + + public struct Output: Sendable { + public var exitCode: Int32 + public var stdout: Data + /// Already redacted. + public var stderr: String + } + + public let binary: URL + public let stateDirectory: URL + private let limiter: AsyncLimiter + + public init(binary: URL, stateDirectory: URL, maxConcurrent: Int = 3) { + self.binary = binary + self.stateDirectory = stateDirectory + self.limiter = AsyncLimiter(limit: maxConcurrent) + } + + /// The child's whole environment. Nothing is inherited but locale/PATH basics. + nonisolated func childEnvironment(_ extra: [String: String]) -> [String: String] { + let parent = ProcessInfo.processInfo.environment + var env: [String: String] = [ + "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", + "HOME": parent["HOME"] ?? NSHomeDirectory(), + "LANG": parent["LANG"] ?? "en_US.UTF-8", + "NO_COLOR": "1", + // Baselines live in the app's container, separate from the CLI's. + "XDG_STATE_HOME": stateDirectory.path, + "XDG_CONFIG_HOME": stateDirectory.appendingPathComponent("config").path, + ] + if let tmp = parent["TMPDIR"] { env["TMPDIR"] = tmp } + // SSH tunnels need the agent socket (the user opts in per bot). + if extra["PGBOT_SSH_TUNNEL"] != nil, let sock = parent["SSH_AUTH_SOCK"] { env["SSH_AUTH_SOCK"] = sock } + env.merge(extra) { $1 } + return env + } + + public func run(_ inv: Invocation) async throws -> Output { + try await limiter.withPermit { + try await self.execute(inv) + } + } + + private func execute(_ inv: Invocation) async throws -> Output { + try Task.checkCancellation() + guard FileManager.default.isExecutableFile(atPath: binary.path) else { throw EngineError.engineMissing(binary.path) } + try? FileManager.default.createDirectory(at: stateDirectory, withIntermediateDirectories: true) + + let process = Process() + process.executableURL = binary + process.arguments = inv.arguments + process.environment = childEnvironment(inv.environment) + process.currentDirectoryURL = stateDirectory + let out = Pipe(), err = Pipe(), input = Pipe() + process.standardOutput = out + process.standardError = err + process.standardInput = input + + // Drain both pipes concurrently so a chatty child can't deadlock on a full buffer. + let stdoutTask = Task.detached { out.fileHandleForReading.readDataToEndOfFile() } + let stderrTask = Task.detached { err.fileHandleForReading.readDataToEndOfFile() } + + let box = ProcessBox(process) + let exit: Int32 = try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in + process.terminationHandler = { p in cont.resume(returning: p.terminationStatus) } + do { try process.run() } catch { + process.terminationHandler = nil + cont.resume(throwing: EngineError.launchFailed(error.localizedDescription)); return + } + if let data = inv.stdin { input.fileHandleForWriting.write(data) } + try? input.fileHandleForWriting.close() + Task.detached { [timeout = inv.timeout] in + try? await Task.sleep(for: timeout) + if box.isRunning { box.timedOut = true; box.stop() } + } + } + } onCancel: { + box.stop() + } + + let stdout = await stdoutTask.value + let rawErr = String(decoding: await stderrTask.value, as: UTF8.self) + let stderr = Redactor.scrub(rawErr, secrets: inv.secrets) + if Task.isCancelled { throw CancellationError() } + if box.timedOut { throw EngineError.timedOut(seconds: Int(inv.timeout.components.seconds)) } + return Output(exitCode: exit, stdout: stdout, stderr: stderr) + } + + /// `pgbot --version` → "0.11.1". + public func version() async throws -> String { + let o = try await run(.init(arguments: ["--version"], timeout: .seconds(10))) + let text = String(decoding: o.stdout, as: UTF8.self) + return text.split(separator: " ").last.map { String($0).trimmingCharacters(in: .whitespacesAndNewlines) } ?? text + } +} + +/// Holds the Process for cancellation from other threads. +final class ProcessBox: @unchecked Sendable { + let process: Process + var timedOut = false + init(_ p: Process) { process = p } + var isRunning: Bool { process.isRunning } + func stop() { + guard process.isRunning else { return } + process.terminate() // SIGTERM: the engine closes its read-only transaction cleanly + let pid = process.processIdentifier + DispatchQueue.global().asyncAfter(deadline: .now() + 3) { [process] in + if process.isRunning { kill(pid, SIGKILL) } + } + } +} + +/// A FIFO counting semaphore for async code. +public actor AsyncLimiter { + private let limit: Int + private var inUse = 0 + private var waiters: [CheckedContinuation] = [] + public init(limit: Int) { self.limit = max(1, limit) } + + public func withPermit(_ body: @Sendable () async throws -> T) async throws -> T { + await acquire() + defer { release() } + return try await body() + } + + private func acquire() async { + if inUse < limit { inUse += 1; return } + await withCheckedContinuation { waiters.append($0) } + } + + private func release() { + if waiters.isEmpty { inUse -= 1 } else { waiters.removeFirst().resume() } + } + + public var active: Int { inUse } +} + +/// User-facing engine failures. Every case carries a plain explanation and a next step. +public enum EngineError: LocalizedError, Equatable { + case engineMissing(String) + case launchFailed(String) + case timedOut(seconds: Int) + case incompatibleSchema(found: String) + case connection(ConnectionProblem, detail: String) + case failed(String) + case invalidOutput(String) + case aiNotConfigured + case aiFailed(String) + + public enum ConnectionProblem: String, Sendable { + case unreachable, authentication, ssl, permission, databaseMissing, timeout, other + } + + public var title: String { + switch self { + case .engineMissing: "PGBot engine not found" + case .launchFailed: "Couldn't start the PGBot engine" + case .timedOut: "The inspection took too long" + case .incompatibleSchema: "Engine version mismatch" + case .connection(let p, _): + switch p { + case .unreachable: "Database unreachable" + case .authentication: "Invalid credentials" + case .ssl: "SSL connection failed" + case .permission: "Insufficient permissions" + case .databaseMissing: "Database not found" + case .timeout: "Connection timed out" + case .other: "Couldn't connect" + } + case .failed: "The engine reported an error" + case .invalidOutput: "Unexpected engine output" + case .aiNotConfigured: "No AI provider configured" + case .aiFailed: "The AI provider returned an error" + } + } + + public var hint: String { + switch self { + case .engineMissing: "Reinstall PGBot, or set the engine path in Settings → Advanced." + case .launchFailed: "Check that the bundled engine isn't quarantined, then try again." + case .timedOut(let s): "No result after \(s)s. The database may be under heavy load; try again or raise the statement timeout." + case .incompatibleSchema: "Update PGBot so the app and the engine agree on the report format." + case .connection(let p, _): + switch p { + case .unreachable: "Check the host and port, and that this Mac can reach the server (VPN, firewall, allow-list)." + case .authentication: "Check the user name and password. PGBot recommends a dedicated read-only role." + case .ssl: "Try SSL mode “require”, or “verify-full” with the provider's CA installed." + case .permission: "Grant the role pg_monitor. “Show setup SQL” prints the exact statements." + case .databaseMissing: "Check the database name." + case .timeout: "The server didn't answer in time. Raise the connection timeout or check the network." + case .other: "See details below." + } + case .failed: "See details below." + case .invalidOutput: "Update PGBot; the engine and app may be out of step." + case .aiNotConfigured: "Add an API key in Settings → AI providers, or use a local model through Ollama." + case .aiFailed: "Check the API key and model in Settings → AI providers." + } + } + + public var detail: String { + switch self { + case .engineMissing(let p): p + case .launchFailed(let s), .failed(let s), .invalidOutput(let s), .aiFailed(let s): s + case .connection(_, let d): d + case .incompatibleSchema(let v): "Report schema \(v) is newer than this app understands." + case .timedOut, .aiNotConfigured: "" + } + } + + public var errorDescription: String? { title } + + /// Classifies engine stderr (already redacted) into an actionable problem. + public static func classify(stderr: String) -> EngineError { + let s = stderr.lowercased() + let detail = stderr.trimmingCharacters(in: .whitespacesAndNewlines) + .replacingOccurrences(of: "pgbot: ", with: "") + func has(_ needles: String...) -> Bool { needles.contains { s.contains($0) } } + // SQLSTATE class 28 is invalid authorization: a wrong password (28P01) or a + // role that doesn't exist / may not log in (28000). Check it before the + // generic "connect:" prefix below, which every connection error carries. + if has("password authentication failed", "authentication failed", "no password supplied", "sasl", + "sqlstate 28000", "sqlstate 28p01") || (has("role \"") && has("does not exist")) { + return .connection(.authentication, detail: detail) + } + if has("ssl", "tls", "certificate", "x509") { return .connection(.ssl, detail: detail) } + if has("permission denied", "must be superuser", "pg_monitor", "insufficient privilege") { + return .connection(.permission, detail: detail) + } + if has("does not exist") && has("database") { return .connection(.databaseMissing, detail: detail) } + if has("timeout", "timed out", "deadline exceeded", "i/o timeout") { return .connection(.timeout, detail: detail) } + if has("connection refused", "no such host", "network is unreachable", "dial tcp", "lookup ", "connect:") { + return .connection(.unreachable, detail: detail) + } + if has("no ai", "api key", "pgbot_ai", "no provider", "ai provider") { return .aiNotConfigured } + return .failed(detail.isEmpty ? "The engine exited without explaining why." : detail) + } +} diff --git a/desktop/macos/Sources/PGBotKit/Engine/PGBotEngine.swift b/desktop/macos/Sources/PGBotKit/Engine/PGBotEngine.swift new file mode 100644 index 0000000..31d6510 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Engine/PGBotEngine.swift @@ -0,0 +1,167 @@ +import Foundation + +/// The desktop app's only way to learn anything about a database: typed calls +/// onto the existing pgbot CLI's machine contracts. No diagnostics live in Swift. +public protocol DiagnosticEngine: Sendable { + func version() async throws -> String + func inspect(_ target: EngineTarget) async throws -> EngineContext + func ask(_ target: EngineTarget, question: String, ai: AIConfiguration, apiKey: String?) async throws -> String + func explainSQL(_ target: EngineTarget, sql: String) async throws -> String + func logs(_ target: EngineTarget, last: Int) async throws -> [LogEntry] + func activity(_ target: EngineTarget) async throws -> [SessionRow] + func why(_ target: EngineTarget, fingerprint: String) async throws -> String + func diff(_ target: EngineTarget, since: String) async throws -> String + func setupSQL(role: String, database: String, includeLogs: Bool) async throws -> String + func runSQL(_ target: EngineTarget, sql: String, maxRows: Int) async throws -> SQLRunOutput +} + +/// What the engine needs to reach one database. Holds the secret DSN in memory +/// only for the duration of a call. +public struct EngineTarget: Sendable { + public var dsn: String + public var password: String? + public var sshTunnel: String? + public init(dsn: String, password: String?, sshTunnel: String? = nil) { + self.dsn = dsn; self.password = password; self.sshTunnel = sshTunnel + } + + public init(connection: DatabaseConnection, password: String?) { + self.init(dsn: ConnectionString.build(connection, password: password), password: password) + } + + var environment: [String: String] { + var env = ["PGBOT_DATABASE_URL": dsn] + if let t = sshTunnel, !t.isEmpty { env["PGBOT_SSH_TUNNEL"] = t } + return env + } + + var secrets: [String] { [dsn] + [password].compactMap { $0 } } +} + +public struct PGBotEngine: DiagnosticEngine { + /// Contract majors this build understands (schema/pgbot-context-1.x). + public static let supportedSchemaMajor = 1 + public let runner: EngineRunner + + public init(runner: EngineRunner) { self.runner = runner } + + public func version() async throws -> String { try await runner.version() } + + public func inspect(_ t: EngineTarget) async throws -> EngineContext { + let out = try await runner.run(.init( + arguments: ["inspect", "--json", "--window", "3s"], + environment: t.environment, timeout: .seconds(120), secrets: t.secrets)) + // 0 = clean, 1 = warnings, 2 = criticals — all are successful inspections. + guard [0, 1, 2].contains(out.exitCode), !out.stdout.isEmpty else { + throw EngineError.classify(stderr: out.stderr) + } + let ctx: EngineContext + do { ctx = try EngineJSON.decodeContext(out.stdout) } catch { + throw EngineError.invalidOutput("Could not read the inspection report: \(error.localizedDescription)") + } + guard ctx.schemaMajor == Self.supportedSchemaMajor else { throw EngineError.incompatibleSchema(found: ctx.schemaVersion) } + return ctx + } + + public func ask(_ t: EngineTarget, question: String, ai: AIConfiguration, apiKey: String?) async throws -> String { + if ai.provider.needsKey && (apiKey ?? "").isEmpty { throw EngineError.aiNotConfigured } + // --yes: the app has already shown its own disclosure and recorded consent. + let out = try await runner.run(.init( + arguments: ["ask", "--yes", "--window", "2s", question], + environment: t.environment.merging(ai.environment(apiKey: apiKey)) { $1 }, + timeout: .seconds(240), secrets: t.secrets + [apiKey].compactMap { $0 })) + let text = String(decoding: out.stdout, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) + guard out.exitCode == 0, !text.isEmpty else { + let err = EngineError.classify(stderr: out.stderr) + if case .failed(let d) = err { throw EngineError.aiFailed(d) } + throw err + } + // The engine already redacts its own output; this guards an echo of a pasted secret. + return Redactor.scrub(text, secrets: t.secrets + [apiKey].compactMap { $0 }) + } + + public func explainSQL(_ t: EngineTarget, sql: String) async throws -> String { + // SQL travels on stdin: it can carry literals and must not show in `ps`. + let out = try await runner.run(.init( + arguments: ["sql", "explain", "--no-color"], environment: t.environment, + stdin: Data(sql.utf8), timeout: .seconds(60), secrets: t.secrets)) + guard out.exitCode == 0 else { throw EngineError.classify(stderr: out.stderr) } + return String(decoding: out.stdout, as: UTF8.self) + } + + public func logs(_ t: EngineTarget, last: Int) async throws -> [LogEntry] { + let out = try await runner.run(.init( + arguments: ["logs", "--json", "--last", String(last)], environment: t.environment, + timeout: .seconds(45), secrets: t.secrets)) + guard out.exitCode == 0 else { throw EngineError.classify(stderr: out.stderr) } + return EngineJSON.decodeLines(LogEntry.self, from: out.stdout) + } + + public func activity(_ t: EngineTarget) async throws -> [SessionRow] { + let out = try await runner.run(.init( + arguments: ["activity", "--json"], environment: t.environment, timeout: .seconds(30), secrets: t.secrets)) + guard out.exitCode == 0 else { throw EngineError.classify(stderr: out.stderr) } + return EngineJSON.decodeLines(SessionRow.self, from: out.stdout) + } + + public func why(_ t: EngineTarget, fingerprint: String) async throws -> String { + let out = try await runner.run(.init( + arguments: ["why", "--no-color", "--fingerprint", fingerprint, "--window", "168h"], + environment: t.environment, timeout: .seconds(60), secrets: t.secrets)) + guard out.exitCode == 0 else { throw EngineError.classify(stderr: out.stderr) } + return String(decoding: out.stdout, as: UTF8.self) + } + + public func diff(_ t: EngineTarget, since: String) async throws -> String { + let out = try await runner.run(.init( + arguments: ["diff", "--since", since], environment: t.environment, timeout: .seconds(120), secrets: t.secrets)) + guard [0, 1, 2].contains(out.exitCode) else { throw EngineError.classify(stderr: out.stderr) } + return String(decoding: out.stdout, as: UTF8.self) + } + + /// `pgbot sql run --json`: the user's own SQL in a READ ONLY transaction that + /// is always rolled back. SQL travels on stdin. A statement error still + /// returns output (with `error` set); only connection problems throw. + public func runSQL(_ t: EngineTarget, sql: String, maxRows: Int = 500) async throws -> SQLRunOutput { + let out = try await runner.run(.init( + arguments: ["sql", "run", "--json", "--max-rows", String(maxRows), "--statement-timeout", "30s"], + environment: t.environment, stdin: Data(sql.utf8), timeout: .seconds(120), secrets: t.secrets)) + if !out.stdout.isEmpty, let parsed = try? JSONDecoder().decode(SQLRunOutput.self, from: out.stdout) { + return parsed + } + if out.exitCode == 64 { + return SQLRunOutput(results: [], error: SQLRunError(message: out.stderr.replacingOccurrences(of: "pgbot: ", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines)), elapsedMS: 0) + } + throw EngineError.classify(stderr: out.stderr) + } + + /// `pgbot init` without a connection: prints the read-only role recipe. + public func setupSQL(role: String, database: String, includeLogs: Bool) async throws -> String { + var args = ["init", "--role", role, "--database", database] + if includeLogs { args.append("--logs") } + let out = try await runner.run(.init(arguments: args, timeout: .seconds(15))) + guard out.exitCode == 0 else { throw EngineError.classify(stderr: out.stderr) } + return String(decoding: out.stdout, as: UTF8.self) + } +} + +/// Where to find the engine: an override, the app bundle, then a CLI install. +public enum EngineLocator { + public static func locate(override: String? = nil, bundle: Bundle = .main) -> URL? { + var candidates: [String] = [] + if let o = override, !o.isEmpty { candidates.append((o as NSString).expandingTildeInPath) } + if let env = ProcessInfo.processInfo.environment["PGBOT_ENGINE_PATH"] { candidates.append(env) } + if let res = bundle.resourceURL?.appendingPathComponent("engine/pgbot").path { candidates.append(res) } + if let exe = bundle.executableURL?.deletingLastPathComponent().appendingPathComponent("pgbot").path { candidates.append(exe) } + candidates += ["/opt/homebrew/bin/pgbot", "/usr/local/bin/pgbot", NSHomeDirectory() + "/go/bin/pgbot"] + return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }.map(URL.init(fileURLWithPath:)) + } +} + +// MARK: - Check hooks (used by PGBotKitChecks; not part of the app's surface) + +public extension EngineTarget { + var environmentForChecks: [String: String] { environment } + var secretsForChecks: [String] { secrets } +} diff --git a/desktop/macos/Sources/PGBotKit/Models/HealthScore.swift b/desktop/macos/Sources/PGBotKit/Models/HealthScore.swift new file mode 100644 index 0000000..6f59f9d --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Models/HealthScore.swift @@ -0,0 +1,99 @@ +import Foundation + +/// The 0–100 health grade. +/// +/// This is the engine's own formula — `render.HealthScore` in +/// internal/render/dashboard.go, the number `pgbot inspect` and `pgbot report` +/// print: 100 minus 10 per critical, 3 per warning, 1 per info finding, skipping +/// suppressed findings, floored at 0. The engine does not (yet) emit the score in +/// `--json`, so it is mirrored here and pinned by a check against those exact +/// rules; keep the two in lock-step (see `HealthScoreChecks`). +/// +/// Unlike the CLI, the app refuses to show a confident grade when the engine +/// reports that the evidence was incomplete: a database the role cannot see into +/// must not read as "100, healthy". +public struct HealthScore: Codable, Sendable, Equatable { + public enum Completeness: String, Codable, Sendable { + /// Every core section was collected. + case complete + /// Some sections were unavailable; the score covers only what was seen. + case partial + /// Too little was visible to grade the database at all. + case unavailable + } + + public var value: Int + public var critical: Int + public var warnings: Int + public var info: Int + public var completeness: Completeness + /// Why the grade is partial/unavailable, in the engine's words. + public var gaps: [String] + + public init(value: Int, critical: Int, warnings: Int, info: Int, completeness: Completeness, gaps: [String]) { + self.value = value; self.critical = critical; self.warnings = warnings; self.info = info + self.completeness = completeness; self.gaps = gaps + } + + /// The engine formula, applied to engine findings. + public static func engineScore(_ findings: [Finding]) -> Int { + var penalty = 0 + for f in findings where !f.isSuppressed { + switch f.severity { + case .critical: penalty += 10 + case .warn: penalty += 3 + case .info: penalty += 1 + } + } + return max(0, 100 - penalty) + } + + public static func from(_ c: EngineContext) -> HealthScore { + let live = c.findings.filter { !$0.isSuppressed } + var gaps: [String] = [] + let core: [(String, (any EngineSection)?)] = [ + ("Health", c.health), ("Activity", c.activity), ("Tables", c.tables), + ("Indexes", c.indexes), ("Queries", c.queries), ("Replication", c.replication), + ] + var unavailableCore = 0 + for (name, section) in core { + guard let s = section else { continue } + if !s.isAvailable { + unavailableCore += 1 + gaps.append("\(name): \(s.reason ?? "not visible to this role")") + } + } + if c.server.hasPgMonitor == false { + gaps.append("The monitoring role lacks pg_monitor, so some statistics are hidden.") + } + // Health and Activity are the backbone; without both, a grade would be a guess. + let backboneMissing = (c.health.map { !$0.isAvailable } ?? true) && (c.activity.map { !$0.isAvailable } ?? true) + let completeness: Completeness = backboneMissing ? .unavailable : (gaps.isEmpty ? .complete : .partial) + return HealthScore( + value: engineScore(c.findings), + critical: live.filter { $0.severity == .critical }.count, + warnings: live.filter { $0.severity == .warn }.count, + info: live.filter { $0.severity == .info }.count, + completeness: completeness, gaps: gaps) + } +} + +/// Presentation bands. Configurable; these are the defaults from the product spec. +public struct HealthBands: Codable, Sendable, Equatable { + public var green: Int = 90 + public var yellow: Int = 70 + public var orange: Int = 50 + public init() {} + + public enum Band: String, Sendable { case green, yellow, orange, red, gray } + + public func band(for score: HealthScore?) -> Band { + guard let s = score, s.completeness != .unavailable else { return .gray } + switch s.value { + case green...: return .green + case yellow...: return .yellow + case orange...: return .orange + default: return .red + } + } +} diff --git a/desktop/macos/Sources/PGBotKit/Models/Models.swift b/desktop/macos/Sources/PGBotKit/Models/Models.swift new file mode 100644 index 0000000..ebb4c7b --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Models/Models.swift @@ -0,0 +1,398 @@ +import Foundation + +// MARK: - Bot identity + +public enum BotColor: String, Codable, Sendable, CaseIterable, Identifiable { + case blue, green, orange, purple, pink, yellow, red, teal, gray, black + public var id: String { rawValue } + public var label: String { rawValue.capitalized } +} + +public enum AvatarShape: String, Codable, Sendable, CaseIterable { + case circle, roundedSquare +} + +public struct BotAvatar: Codable, Sendable, Equatable, Hashable { + public var color: BotColor + public var shape: AvatarShape + public init(color: BotColor = .blue, shape: AvatarShape = .roundedSquare) { self.color = color; self.shape = shape } +} + +public enum DatabaseEnvironment: String, Codable, Sendable, CaseIterable, Identifiable { + case production, staging, development, local, custom + public var id: String { rawValue } + public var label: String { rawValue.capitalized } +} + +public enum SSLMode: String, Codable, Sendable, CaseIterable, Identifiable { + case disable, allow, prefer, require + case verifyCA = "verify-ca" + case verifyFull = "verify-full" + public var id: String { rawValue } +} + +// MARK: - Connection + +/// Non-secret connection settings. The password lives only in the Keychain, +/// keyed by the bot id; it is never persisted here or written to a log. +public struct DatabaseConnection: Codable, Sendable, Equatable, Hashable { + public var host: String + public var port: Int + public var database: String + public var username: String + public var sslMode: SSLMode + public var connectTimeoutSeconds: Int + /// Extra non-secret libpq parameters from a pasted URL (e.g. options, target_session_attrs). + public var extraParameters: [String: String] + + public init(host: String = "localhost", port: Int = 5432, database: String = "postgres", + username: String = "postgres", sslMode: SSLMode = .prefer, connectTimeoutSeconds: Int = 10, + extraParameters: [String: String] = [:]) { + self.host = host; self.port = port; self.database = database; self.username = username + self.sslMode = sslMode; self.connectTimeoutSeconds = connectTimeoutSeconds; self.extraParameters = extraParameters + } + + /// Server identity, independent of the logical database: one PostgreSQL + /// instance can host many databases (and many bots). + public var instanceKey: String { "\(host.lowercased()):\(port)" } + + /// A display-safe description — no password, no full connection string. + public var safeSummary: String { "\(username)@\(host):\(port)/\(database)" } +} + +/// A PostgreSQL server; several logical databases (bots) may share one. +public struct DatabaseInstance: Codable, Sendable, Equatable, Hashable, Identifiable { + public var id: String // host:port + public var provider: String? // engine-detected: rds, aurora, cloudsql, azure, supabase, neon… + public var versionText: String? +} + +// MARK: - Monitoring + +public struct MonitoringSchedule: Codable, Sendable, Equatable, Hashable { + public var enabled: Bool = true + /// Seconds between background inspections. + public var intervalSeconds: Int = 3600 + /// Hour of day (local) for the daily report, nil = off. + public var dailyReportHour: Int? = 9 + /// Minimum severity that produces a notification. + public var notifyMinimum: Severity = .warn + public var notifyResolved: Bool = true + /// Finding keys (id|object) the user chose to ignore in this app. + public var ignoredFindingKeys: Set = [] + /// Local history retention in days. + public var retentionDays: Int = 30 + public init() {} + + public static let intervalChoices: [(String, Int)] = [ + ("Every 15 minutes", 900), ("Every 30 minutes", 1800), ("Every hour", 3600), + ("Every 6 hours", 21600), ("Every day", 86400), + ] +} + +public enum ScheduledTaskKind: String, Codable, Sendable, CaseIterable { + case inspect, dailyReport, unusedIndexes, slowQueries + public var label: String { + switch self { + case .inspect: "Inspect the database" + case .dailyReport: "Send a morning health report" + case .unusedIndexes: "Check for unused indexes" + case .slowQueries: "Analyze slow queries" + } + } +} + +public struct ScheduledTask: Codable, Sendable, Equatable, Hashable, Identifiable { + public var id: UUID = UUID() + public var kind: ScheduledTaskKind + public var intervalSeconds: Int + public var lastRun: Date? + public init(kind: ScheduledTaskKind, intervalSeconds: Int) { self.kind = kind; self.intervalSeconds = intervalSeconds } +} + +// MARK: - Bot + +public enum ConnectionStatus: String, Codable, Sendable { + case unknown, connecting, healthy, degraded, critical, unreachable, paused +} + +public struct DatabaseBot: Codable, Sendable, Equatable, Hashable, Identifiable { + public var id: UUID + public var displayName: String + public var description: String + public var avatar: BotAvatar + public var environment: DatabaseEnvironment + public var customGroup: String? + public var connection: DatabaseConnection + public var pinned: Bool + public var muted: Bool + public var sortOrder: Int + public var schedule: MonitoringSchedule + public var tasks: [ScheduledTask] + public var createdAt: Date + /// Demo bots carry sample data and never touch a real engine. + public var isDemo: Bool + + // Latest status, cached for the sidebar (the source of truth is the latest inspection). + public var status: ConnectionStatus + public var lastInspectedAt: Date? + public var lastSummary: String? + public var lastScore: Int? + public var unreadCount: Int + + public init(id: UUID = UUID(), displayName: String, description: String = "", avatar: BotAvatar = .init(), + environment: DatabaseEnvironment = .production, customGroup: String? = nil, + connection: DatabaseConnection, pinned: Bool = false, muted: Bool = false, sortOrder: Int = 0, + schedule: MonitoringSchedule = .init(), tasks: [ScheduledTask] = [], createdAt: Date = .now, + isDemo: Bool = false, status: ConnectionStatus = .unknown, lastInspectedAt: Date? = nil, + lastSummary: String? = nil, lastScore: Int? = nil, unreadCount: Int = 0) { + self.id = id; self.displayName = displayName; self.description = description; self.avatar = avatar + self.environment = environment; self.customGroup = customGroup; self.connection = connection + self.pinned = pinned; self.muted = muted; self.sortOrder = sortOrder; self.schedule = schedule + self.tasks = tasks; self.createdAt = createdAt; self.isDemo = isDemo; self.status = status + self.lastInspectedAt = lastInspectedAt; self.lastSummary = lastSummary; self.lastScore = lastScore + self.unreadCount = unreadCount + } + + public var keychainAccount: String { "db:\(id.uuidString)" } + public var groupName: String { customGroup ?? environment.label } +} + +// MARK: - Inspections + +/// One stored engine run for a bot. +public struct InspectionRecord: Codable, Sendable, Equatable, Identifiable { + public var id: UUID + public var botID: UUID + public var startedAt: Date + public var finishedAt: Date + public var context: EngineContext + public var score: HealthScore + public init(id: UUID = UUID(), botID: UUID, startedAt: Date, finishedAt: Date, context: EngineContext) { + self.id = id; self.botID = botID; self.startedAt = startedAt; self.finishedAt = finishedAt + self.context = context; self.score = HealthScore.from(context) + } +} + +/// A point-in-time metric extracted from an inspection, for history charts. +public struct MetricSample: Codable, Sendable, Equatable, Hashable { + public var botID: UUID + public var metric: MetricKey + public var at: Date + public var value: Double + public init(botID: UUID, metric: MetricKey, at: Date, value: Double) { + self.botID = botID; self.metric = metric; self.at = at; self.value = value + } +} + +public enum MetricKey: String, Codable, Sendable, CaseIterable { + case healthScore, connections, connectionUtilization, tps, cacheHitRatio, rollbackRatio + case deadlocksPerMin, dbSizeBytes, walBytesPerSec, replicationLagSec, blockedSessions, tempBytesPerSec + case activeSessions, idleInTransaction + + public var label: String { + switch self { + case .healthScore: "Health score" + case .connections: "Connections" + case .connectionUtilization: "Connection utilization" + case .tps: "Transactions / sec" + case .cacheHitRatio: "Cache hit ratio" + case .rollbackRatio: "Rollback rate" + case .deadlocksPerMin: "Deadlocks / min" + case .dbSizeBytes: "Database size" + case .walBytesPerSec: "WAL generation" + case .replicationLagSec: "Replication lag" + case .blockedSessions: "Blocked sessions" + case .tempBytesPerSec: "Temp file writes" + case .activeSessions: "Active sessions" + case .idleInTransaction: "Idle in transaction" + } + } + + /// Every sample is a direct read of an engine field — nothing is derived + /// beyond unit-free ratios the engine already reports. + public static func samples(from r: InspectionRecord) -> [MetricSample] { + let c = r.context, at = c.collectedAt + var out: [(MetricKey, Double?)] = [ + (.healthScore, r.score.completeness == .unavailable ? nil : Double(r.score.value)), + (.connections, c.limits.map { Double($0.connectionsUsed) }), + (.connectionUtilization, c.limits?.utilization), + (.tps, c.health?.tps), (.cacheHitRatio, c.health?.cacheHitRatio), + (.rollbackRatio, c.health?.rollbackRatio), (.deadlocksPerMin, c.health?.deadlocksPerMin), + (.tempBytesPerSec, c.health?.tempBytesPerSec), + (.dbSizeBytes, c.tables?.dbSizeBytes.map(Double.init)), (.walBytesPerSec, c.wal?.bytesPerSec), + (.blockedSessions, c.locks?.blockedCount.map(Double.init)), + (.activeSessions, c.activity?.active.map(Double.init)), + (.idleInTransaction, c.activity?.idleInTransaction.map(Double.init)), + ] + if let rep = c.replication { + let lags = (rep.replicas ?? []).compactMap(\.replayLagSec) + [rep.receiverLagSec].compactMap { $0 } + out.append((.replicationLagSec, lags.max())) + } + return out.compactMap { k, v in v.map { MetricSample(botID: r.botID, metric: k, at: at, value: $0) } } + } +} + +// MARK: - Conversation + +public enum ChatRole: String, Codable, Sendable { case user, assistant, system } + +/// The structured payload a message renders. Production payloads only ever come +/// from engine output; `.text` from the assistant comes from `pgbot ask`. +public enum MessagePayload: Codable, Sendable, Equatable { + case text(String) + case healthReport(HealthReportPayload) + case finding(Finding, change: FindingChange?) + case findingsList(title: String, findings: [Finding]) + case sql(title: String, sql: String) + case plan(sql: String, reading: String) + case table(title: String, columns: [String], rows: [[String]]) + case metric(MetricKey, points: [MetricPoint]) + case connectionEvent(String, ok: Bool) + case monitoringEvent(String) + case resolved([Finding]) + case error(title: String, detail: String, hint: String?) + /// What the user typed in PSQL mode. + case psqlInput(String) + /// Results of `pgbot sql run` (read-only), or a console notice. + case psqlResult(PSQLResultPayload) +} + +public enum FindingChange: String, Codable, Sendable { case new, escalated, deescalated, resolved } + +public struct MetricPoint: Codable, Sendable, Equatable, Hashable { + public var at: Date + public var value: Double + public init(at: Date, value: Double) { self.at = at; self.value = value } +} + +public struct HealthReportPayload: Codable, Sendable, Equatable { + public var headline: String + public var score: HealthScore + public var previousScore: Int? + public var findings: [Finding] + public var resolvedCount: Int + public var serverVersion: String + public var inspectedAt: Date + public var isScheduled: Bool + /// Optional so reports saved by earlier versions still decode. + public var isFirstRun: Bool? + public init(headline: String, score: HealthScore, previousScore: Int?, findings: [Finding], + resolvedCount: Int, serverVersion: String, inspectedAt: Date, isScheduled: Bool, isFirstRun: Bool? = nil) { + self.isFirstRun = isFirstRun + self.headline = headline; self.score = score; self.previousScore = previousScore; self.findings = findings + self.resolvedCount = resolvedCount; self.serverVersion = serverVersion; self.inspectedAt = inspectedAt + self.isScheduled = isScheduled + } +} + +public struct ChatMessage: Codable, Sendable, Equatable, Identifiable { + public var id: UUID + public var botID: UUID + public var role: ChatRole + public var payload: MessagePayload + public var createdAt: Date + /// For assistant answers: the question that produced it (enables Regenerate). + public var inReplyTo: UUID? + public var modelName: String? + + public init(id: UUID = UUID(), botID: UUID, role: ChatRole, payload: MessagePayload, createdAt: Date = .now, + inReplyTo: UUID? = nil, modelName: String? = nil) { + self.id = id; self.botID = botID; self.role = role; self.payload = payload; self.createdAt = createdAt + self.inReplyTo = inReplyTo; self.modelName = modelName + } + + /// Plain text for search, copy, and export. + public var plainText: String { + switch payload { + case .text(let s): return s + case .healthReport(let r): return "\(r.headline)\nHealth score \(r.score.value)/100\n" + r.findings.map { "• \($0.title)" }.joined(separator: "\n") + case .finding(let f, _): return "\(f.title)\n\(f.detail)" + case .findingsList(let t, let fs): return t + "\n" + fs.map { "• \($0.title)" }.joined(separator: "\n") + case .sql(let t, let s): return "\(t)\n\(s)" + case .plan(let s, let r): return "\(s)\n\n\(r)" + case .table(let t, let cols, let rows): return ([t, cols.joined(separator: "\t")] + rows.map { $0.joined(separator: "\t") }).joined(separator: "\n") + case .metric(let k, _): return k.label + case .connectionEvent(let s, _), .monitoringEvent(let s): return s + case .resolved(let fs): return "Resolved: " + fs.map(\.title).joined(separator: ", ") + case .error(let t, let d, let h): return [t, d, h ?? ""].joined(separator: "\n") + case .psqlInput(let s): return s + case .psqlResult(let r): return r.plainText + } + } +} + +// MARK: - Notifications + +public enum NotificationCategory: String, Codable, Sendable, CaseIterable { + case criticalFinding, warning, scoreChange, regression, connectivity, resolved, scheduledReport + public var label: String { + switch self { + case .criticalFinding: "Critical findings" + case .warning: "New warnings" + case .scoreChange: "Health score changes" + case .regression: "Performance regressions" + case .connectivity: "Connectivity failures" + case .resolved: "Resolved issues" + case .scheduledReport: "Scheduled reports" + } + } +} + +public struct AppNotification: Codable, Sendable, Equatable, Identifiable { + public var id: UUID + public var botID: UUID + public var category: NotificationCategory + public var severity: Severity + public var title: String + public var body: String + public var createdAt: Date + public var read: Bool + /// The message to scroll to when opened. + public var messageID: UUID? + /// Dedup key: same bot + key is not re-announced until its state changes. + public var dedupKey: String + public init(id: UUID = UUID(), botID: UUID, category: NotificationCategory, severity: Severity, title: String, + body: String, createdAt: Date = .now, read: Bool = false, messageID: UUID? = nil, dedupKey: String) { + self.id = id; self.botID = botID; self.category = category; self.severity = severity; self.title = title + self.body = body; self.createdAt = createdAt; self.read = read; self.messageID = messageID; self.dedupKey = dedupKey + } +} + +public struct QuietHours: Codable, Sendable, Equatable { + public var enabled: Bool = false + public var startHour: Int = 22 + public var endHour: Int = 7 + public init() {} + public func contains(_ date: Date, calendar: Calendar = .current) -> Bool { + guard enabled else { return false } + let h = calendar.component(.hour, from: date) + return startHour <= endHour ? (h >= startHour && h < endHour) : (h >= startHour || h < endHour) + } +} + +// MARK: - Account + +public enum AuthProvider: String, Codable, Sendable, CaseIterable { case google, github, local } + +public struct User: Codable, Sendable, Equatable { + public var id: String + public var name: String + public var email: String? + public var avatarURL: URL? + public var provider: AuthProvider + public init(id: String, name: String, email: String?, avatarURL: URL?, provider: AuthProvider) { + self.id = id; self.name = name; self.email = email; self.avatarURL = avatarURL; self.provider = provider + } +} + +public enum SubscriptionPlan: String, Codable, Sendable { case free, pro } + +public struct Subscription: Codable, Sendable, Equatable { + public var plan: SubscriptionPlan = .free + public init() {} + /// Everything diagnostic is free; Pro gates only future cloud capabilities. + public func allows(_ feature: ProFeature) -> Bool { plan == .pro } +} + +public enum ProFeature: String, Sendable { case cloudMonitoring, slack, email, webhooks, teams, extendedHistory } diff --git a/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift b/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift new file mode 100644 index 0000000..d0f4fa5 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift @@ -0,0 +1,126 @@ +import Foundation + +/// What moved between two inspections — the same semantics as the engine's +/// monitor.Compare (internal/monitor/decide.go): identity is id+object, never +/// the title; suppressed findings are invisible. +public struct FindingChanges: Sendable, Equatable { + public var new: [Finding] = [] + public var escalated: [Finding] = [] + public var deescalated: [Finding] = [] + /// Carries the OLD finding (its last known severity and wording). + public var resolved: [Finding] = [] + public var unchanged: [Finding] = [] + public init() {} + + public var isEmpty: Bool { new.isEmpty && escalated.isEmpty && deescalated.isEmpty && resolved.isEmpty } + + public static func compare(previous: [Finding], current: [Finding], ignoring ignored: Set = []) -> FindingChanges { + let prev = previous.filter { !$0.isSuppressed && !ignored.contains($0.key) } + let cur = current.filter { !$0.isSuppressed && !ignored.contains($0.key) } + var before = Dictionary(prev.map { ($0.key, $0) }, uniquingKeysWith: { a, _ in a }) + var ch = FindingChanges() + for f in cur { + if let old = before.removeValue(forKey: f.key) { + if f.severity > old.severity { ch.escalated.append(f) } + else if f.severity < old.severity { ch.deescalated.append(f) } + else { ch.unchanged.append(f) } + } else { + ch.new.append(f) + } + } + ch.resolved = prev.filter { before[$0.key] != nil } + let order: (Finding, Finding) -> Bool = { ($0.severity.rank, $0.impact?.score ?? 0) > ($1.severity.rank, $1.impact?.score ?? 0) } + ch.new.sort(by: order); ch.escalated.sort(by: order); ch.deescalated.sort(by: order) + ch.resolved.sort(by: order); ch.unchanged.sort(by: order) + return ch + } + + /// New + escalated at or above a minimum severity. + public func worsened(minimum: Severity) -> [Finding] { + (escalated + new).filter { $0.severity >= minimum } + } +} + +/// Remembers what was announced per bot so an unchanged finding is never +/// announced twice — across restarts, failed runs in between, and flapping. +public struct AnnouncementLedger: Codable, Sendable, Equatable { + /// finding key → severity last announced + public var announced: [String: Severity] = [:] + public var connectivityDown = false + public var lastDailyReport: Date? + public init() {} +} + +public struct PlannedNotification: Sendable, Equatable { + public var category: NotificationCategory + public var severity: Severity + public var title: String + public var body: String + public var dedupKey: String + public var findingKey: String? + public init(category: NotificationCategory, severity: Severity, title: String, body: String, dedupKey: String, findingKey: String? = nil) { + self.category = category; self.severity = severity; self.title = title; self.body = body + self.dedupKey = dedupKey; self.findingKey = findingKey + } +} + +/// Decides which notifications an inspection produces. Pure; the app delivers them. +public enum NotificationPlanner { + public struct Preferences: Sendable, Equatable { + public var minimum: Severity + public var notifyResolved: Bool + public var disabled: Set + public init(minimum: Severity = .warn, notifyResolved: Bool = true, disabled: Set = []) { + self.minimum = minimum; self.notifyResolved = notifyResolved; self.disabled = disabled + } + } + + public static func plan(botName: String, changes: FindingChanges, scoreBefore: Int?, scoreAfter: HealthScore, + ledger: inout AnnouncementLedger, prefs: Preferences) -> [PlannedNotification] { + var out: [PlannedNotification] = [] + + for f in changes.worsened(minimum: prefs.minimum) where ledger.announced[f.key] != f.severity { + ledger.announced[f.key] = f.severity + let cat: NotificationCategory = f.severity == .critical ? .criticalFinding : (isRegression(f) ? .regression : .warning) + let verb = changes.escalated.contains(f) ? "escalated to \(f.severity.label.lowercased())" : f.severity.label + out.append(.init(category: cat, severity: f.severity, title: "\(botName) — \(verb)", + body: f.title, dedupKey: "\(f.key)|\(f.severity.rawValue)", findingKey: f.key)) + } + // De-escalations update the ledger silently; they're not alarms. + for f in changes.deescalated { ledger.announced[f.key] = f.severity } + + let resolvedAnnounced = changes.resolved.filter { ledger.announced[$0.key] != nil } + for f in changes.resolved { ledger.announced.removeValue(forKey: f.key) } + if prefs.notifyResolved, !resolvedAnnounced.isEmpty { + let body = resolvedAnnounced.count == 1 ? resolvedAnnounced[0].title : "\(resolvedAnnounced.count) issues resolved" + out.append(.init(category: .resolved, severity: .info, title: "\(botName) — resolved", body: body, + dedupKey: "resolved|" + resolvedAnnounced.map(\.key).sorted().joined(separator: ","), findingKey: nil)) + } + + if let before = scoreBefore, scoreAfter.completeness != .unavailable, before - scoreAfter.value >= 10 { + out.append(.init(category: .scoreChange, severity: .warn, title: "\(botName) — health score dropped", + body: "Health score went from \(before) to \(scoreAfter.value).", + dedupKey: "score|\(scoreAfter.value)", findingKey: nil)) + } + if ledger.connectivityDown { + ledger.connectivityDown = false + out.append(.init(category: .resolved, severity: .info, title: "\(botName) — reachable again", + body: "PGBot reconnected and finished an inspection.", dedupKey: "connectivity|up", findingKey: nil)) + } + return out.filter { !prefs.disabled.contains($0.category) } + } + + /// A failed run announces an outage once, not every retry. + public static func planFailure(botName: String, error: EngineError, ledger: inout AnnouncementLedger, + prefs: Preferences) -> PlannedNotification? { + guard !ledger.connectivityDown, !prefs.disabled.contains(.connectivity) else { return nil } + guard case .connection = error else { return nil } + ledger.connectivityDown = true + return .init(category: .connectivity, severity: .critical, title: "\(botName) — \(error.title.lowercased())", + body: error.hint, dedupKey: "connectivity|down", findingKey: nil) + } + + static func isRegression(_ f: Finding) -> Bool { + f.impact?.dimension == "latency" || f.id.contains("regress") || f.id.contains("slow") + } +} diff --git a/desktop/macos/Sources/PGBotKit/Monitoring/ReportComposer.swift b/desktop/macos/Sources/PGBotKit/Monitoring/ReportComposer.swift new file mode 100644 index 0000000..084579b --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Monitoring/ReportComposer.swift @@ -0,0 +1,148 @@ +import Foundation + +/// Turns engine output into conversation messages. Every number and sentence +/// comes from the engine's findings; this only chooses what to say first. +public enum ReportComposer { + public static func healthReport(bot: DatabaseBot, record: InspectionRecord, previous: InspectionRecord?, + firstRun: Bool, scheduled: Bool) -> ChatMessage { + let live = record.context.findings.filter { !$0.isSuppressed && !bot.schedule.ignoredFindingKeys.contains($0.key) } + let notable = live.filter { $0.severity >= .warn } + let changes = previous.map { FindingChanges.compare(previous: $0.context.findings, current: record.context.findings) } + // One sentence; the card supplies its own title ("Your daily database report", …). + let criticals = notable.filter { $0.severity == .critical }.count + let issues = notable.count == 1 ? "one issue" : "\(spelled(notable.count)) issues" + let headline: String + if record.score.completeness == .unavailable { + headline = "I connected, but this role can't see enough to grade the database." + } else if notable.isEmpty { + headline = firstRun ? "I analyzed your database and didn't find anything that needs attention." + : "Your database is healthy. No warnings or critical findings." + } else if criticals > 0 { + headline = "I found \(issues) that need attention, including \(criticals == 1 ? "one critical finding" : "\(spelled(criticals)) critical findings")." + } else { + headline = firstRun ? "I analyzed your database and found \(issues) worth reviewing." + : "Your database is healthy overall, but I found \(issues) worth reviewing." + } + let payload = HealthReportPayload( + headline: headline, score: record.score, previousScore: previous?.score.value, + findings: live.sorted { ($0.severity.rank, $0.impact?.score ?? 0) > ($1.severity.rank, $1.impact?.score ?? 0) }, + resolvedCount: changes?.resolved.count ?? 0, + serverVersion: record.context.server.displayVersion, inspectedAt: record.finishedAt, isScheduled: scheduled, + isFirstRun: firstRun) + return ChatMessage(botID: bot.id, role: .assistant, payload: .healthReport(payload), createdAt: record.finishedAt) + } + + static func spelled(_ n: Int) -> String { + let words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] + return n < words.count ? words[n] : "\(n)" + } + + /// Proactive messages for a background run: only what changed, never a repeat. + public static func proactive(bot: DatabaseBot, changes: FindingChanges, at: Date) -> [ChatMessage] { + var out: [ChatMessage] = [] + for f in changes.escalated { out.append(.init(botID: bot.id, role: .assistant, payload: .finding(f, change: .escalated), createdAt: at)) } + for f in changes.new where f.severity >= .warn { out.append(.init(botID: bot.id, role: .assistant, payload: .finding(f, change: .new), createdAt: at)) } + if !changes.resolved.isEmpty { out.append(.init(botID: bot.id, role: .assistant, payload: .resolved(changes.resolved), createdAt: at)) } + return out + } + + /// One-line sidebar summary: "2 new findings · Lock contention" / "Healthy · Last checked …". + public static func sidebarSummary(record: InspectionRecord, changes: FindingChanges?) -> String { + let live = record.context.findings.filter { !$0.isSuppressed } + if record.score.completeness == .unavailable { return "Limited visibility · grant pg_monitor" } + let crit = live.filter { $0.severity == .critical }, warn = live.filter { $0.severity == .warn } + if let top = (crit + warn).first { + let newCount = changes?.worsened(minimum: .warn).count ?? 0 + let lead = !crit.isEmpty ? "\(crit.count) critical" : (newCount > 0 ? "\(newCount) new" : "\(warn.count) warning\(warn.count == 1 ? "" : "s")") + return "\(lead) · \(shortTitle(top.title))" + } + return "Healthy · No new findings" + } + + static func shortTitle(_ s: String) -> String { s.count > 42 ? String(s.prefix(40)) + "…" : s } + + /// Tabular payloads for deterministic plus-menu actions, read from the latest inspection. + public static func queriesTable(_ c: EngineContext, sortBy: KeyPath = \.totalMS, title: String) -> MessagePayload { + guard let q = c.queries, q.isAvailable, let top = q.top, !top.isEmpty else { + return .error(title: "Query statistics unavailable", + detail: c.queries?.reason ?? "pg_stat_statements isn't enabled for this database.", + hint: "Enable the pg_stat_statements extension (Show setup SQL lists the provider-specific steps).") + } + let rows = top.sorted { $0[keyPath: sortBy] > $1[keyPath: sortBy] }.prefix(10).map { + [Format.ms($0.totalMS), Format.ms($0.meanMS), Format.count($0.calls), Format.sqlPreview($0.query)] + } + return .table(title: title, columns: ["Total", "Mean", "Calls", "Query"], rows: Array(rows)) + } + + public static func indexesTable(_ c: EngineContext) -> MessagePayload { + guard let ix = c.indexes, ix.isAvailable else { + return .error(title: "Index statistics unavailable", detail: c.indexes?.reason ?? "Not collected.", hint: nil) + } + let unused = ix.unused ?? [] + if unused.isEmpty { + return .text("No potentially unused indexes among the \(ix.total ?? 0) indexes inspected.") + } + let rows = unused.prefix(15).map { [$0.schema + "." + $0.name, $0.table, Format.bytes($0.bytes), Format.count($0.scans)] } + return .table(title: "Potentially unused indexes (\(Format.bytes(unused.reduce(0) { $0 + $1.bytes })))", + columns: ["Index", "Table", "Size", "Scans"], rows: Array(rows)) + } + + public static func locksTable(_ c: EngineContext) -> MessagePayload { + guard let l = c.locks, l.isAvailable else { + return .error(title: "Lock information unavailable", detail: c.locks?.reason ?? "Not collected.", hint: nil) + } + let chains = l.chains ?? [] + if chains.isEmpty { return .text("No blocked sessions at the time of the last inspection.") } + return .table(title: "\(l.blockedCount ?? chains.count) blocked session(s)", columns: ["Blocked PID", "Blocked by", "Waiting", "Query"], + rows: chains.map { ["\($0.blockedPID)", $0.blockingPIDs.map(String.init).joined(separator: ", "), + Format.seconds($0.waitSeconds), Format.sqlPreview($0.blockedQuery)] }) + } + + public static func replicationTable(_ c: EngineContext) -> MessagePayload { + guard let r = c.replication, r.isAvailable else { + return .error(title: "Replication information unavailable", detail: c.replication?.reason ?? "Not collected.", hint: nil) + } + var rows: [[String]] = (r.replicas ?? []).map { + ["Replica \($0.appName ?? $0.clientAddr)", $0.state, $0.replayLagSec.map(Format.seconds) ?? "idle", $0.syncState] + } + rows += (r.slots ?? []).map { ["Slot \($0.name)", $0.active ? "active" : "inactive", Format.bytes($0.retainedBytes) + " retained", $0.type] } + if let lag = r.receiverLagSec { rows.append(["This standby", "receiving", Format.seconds(lag), "—"]) } + if rows.isEmpty { return .text(r.isReplica == true ? "This is a standby with no lag reported." : "No replicas or replication slots are configured.") } + return .table(title: "Replication", columns: ["Member", "State", "Lag", "Mode"], rows: rows) + } + + public static func sessionsTable(_ s: [SessionRow]) -> MessagePayload { + if s.isEmpty { return .text("No client sessions right now.") } + let rows = s.sorted { ($0.xactAgeS ?? 0) > ($1.xactAgeS ?? 0) }.prefix(20).map { + ["\($0.pid)", $0.user ?? "", $0.state, $0.wait ?? "", $0.xactAgeS.map(Format.seconds) ?? "", Format.sqlPreview($0.query ?? "")] + } + return .table(title: "\(s.count) session(s)", columns: ["PID", "User", "State", "Wait", "Xact age", "Query"], rows: Array(rows)) + } +} + +/// Shared, locale-aware formatting. +public enum Format { + public static func bytes(_ b: Int64) -> String { + let f = ByteCountFormatter() + f.countStyle = .binary + f.allowsNonnumericFormatting = false // "0 bytes", not "Zero KB" + return f.string(fromByteCount: b) + } + public static func bytes(_ b: Double) -> String { bytes(Int64(b)) } + public static func count(_ n: Int64) -> String { n.formatted(.number.notation(.compactName)) } + public static func percent(_ r: Double, digits: Int = 1) -> String { (r).formatted(.percent.precision(.fractionLength(digits))) } + public static func ms(_ ms: Double) -> String { + switch ms { + case ..<1: String(format: "%.2f ms", ms) + case ..<1000: String(format: "%.0f ms", ms) + case ..<60_000: String(format: "%.1f s", ms / 1000) + case ..<3_600_000: String(format: "%.1f min", ms / 60_000) + default: String(format: "%.1f h", ms / 3_600_000) + } + } + public static func seconds(_ s: Double) -> String { ms(s * 1000) } + public static func sqlPreview(_ q: String, limit: Int = 90) -> String { + let one = q.split(whereSeparator: \.isWhitespace).joined(separator: " ") + return one.count > limit ? String(one.prefix(limit - 1)) + "…" : one + } +} diff --git a/desktop/macos/Sources/PGBotKit/Monitoring/Scheduler.swift b/desktop/macos/Sources/PGBotKit/Monitoring/Scheduler.swift new file mode 100644 index 0000000..4167024 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Monitoring/Scheduler.swift @@ -0,0 +1,121 @@ +import Foundation + +/// Decides WHEN each bot is inspected. It never runs SQL itself; it calls the +/// `perform` closure, which goes through the engine (and its concurrency limit). +/// +/// Honest about its limits: it runs only while the app process runs and the Mac +/// is awake. On wake it runs each overdue bot once — no catch-up storm, and no +/// claim of coverage for the time the Mac slept. +public actor InspectionScheduler { + public enum Outcome: Sendable { case success, failure } + + public struct Entry: Sendable, Equatable { + public var interval: TimeInterval + public var nextDue: Date + public var consecutiveFailures = 0 + public var paused = false + public var running = false + } + + public typealias Perform = @Sendable (UUID) async -> Outcome + + private var entries: [UUID: Entry] = [:] + private var globallyPaused = false + private var suspendedForSleep = false + private var loop: Task? + private let perform: Perform + private let clock: @Sendable () -> Date + private let maxBackoff: TimeInterval + + public init(maxBackoff: TimeInterval = 6 * 3600, clock: @escaping @Sendable () -> Date = { Date() }, perform: @escaping Perform) { + self.perform = perform; self.clock = clock; self.maxBackoff = maxBackoff + } + + // MARK: Configuration + + public func register(_ id: UUID, interval: TimeInterval, paused: Bool, firstRunAt: Date? = nil) { + let now = clock() + if var e = entries[id] { + e.interval = interval; e.paused = paused + e.nextDue = min(e.nextDue, now.addingTimeInterval(interval)) + entries[id] = e + } else { + entries[id] = Entry(interval: interval, nextDue: firstRunAt ?? now.addingTimeInterval(interval), paused: paused) + } + } + + public func unregister(_ id: UUID) { entries.removeValue(forKey: id) } + public func setPaused(_ id: UUID, _ paused: Bool) { entries[id]?.paused = paused } + public func setGloballyPaused(_ p: Bool) { globallyPaused = p } + public func entry(_ id: UUID) -> Entry? { entries[id] } + public var isGloballyPaused: Bool { globallyPaused } + + // MARK: Sleep / wake + + public func willSleep() { suspendedForSleep = true } + public func didWake() { suspendedForSleep = false } + + // MARK: Running + + public func start(tick: Duration = .seconds(20)) { + loop?.cancel() + loop = Task { [weak self] in + while !Task.isCancelled { + await self?.runDue() + try? await Task.sleep(for: tick) + } + } + } + + public func stop() { loop?.cancel(); loop = nil } + + /// Bots due now, oldest-due first. Exposed for checks. + public func dueIDs() -> [UUID] { + guard !globallyPaused, !suspendedForSleep else { return [] } + let now = clock() + return entries.filter { !$0.value.paused && !$0.value.running && $0.value.nextDue <= now } + .sorted { $0.value.nextDue < $1.value.nextDue }.map(\.key) + } + + /// Runs everything due, concurrently (the engine bounds actual parallelism). + public func runDue() async { + let ids = dueIDs() + for id in ids { entries[id]?.running = true } + await withTaskGroup(of: (UUID, Outcome).self) { group in + for id in ids { group.addTask { [perform] in (id, await perform(id)) } } + for await (id, outcome) in group { record(id, outcome) } + } + } + + /// Run one bot now, outside its schedule ("Run inspection"). + public func runNow(_ id: UUID) async -> Outcome? { + guard var e = entries[id], !e.running else { return nil } + e.running = true; entries[id] = e + let outcome = await perform(id) + record(id, outcome) + return outcome + } + + func record(_ id: UUID, _ outcome: Outcome) { + guard var e = entries[id] else { return } + e.running = false + let now = clock() + switch outcome { + case .success: + e.consecutiveFailures = 0 + e.nextDue = now.addingTimeInterval(e.interval) + case .failure: + e.consecutiveFailures += 1 + e.nextDue = now.addingTimeInterval(Self.backoff(failures: e.consecutiveFailures, interval: e.interval, cap: maxBackoff)) + } + entries[id] = e + } + + /// Retry delay after a failure: 1 min, 2, 4, 8 … — capped at the bot's own + /// interval (a failing bot is never retried less often than it would be + /// inspected when healthy) and at the global cap. + public static func backoff(failures: Int, interval: TimeInterval, cap: TimeInterval) -> TimeInterval { + let exp = 60 * pow(2, Double(max(0, failures - 1))) + return min(exp, max(interval, 60), cap) + } +} diff --git a/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift b/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift new file mode 100644 index 0000000..8ecda04 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift @@ -0,0 +1,312 @@ +import Foundation + +// MARK: - Engine contract: `pgbot sql run --json` (sql_run_schema_version 1.x) + +public struct SQLRunColumn: Codable, Sendable, Equatable, Hashable { + public var name: String + public var type: String + public init(name: String, type: String) { self.name = name; self.type = type } + + /// Right-align numbers, like psql. + public var isNumeric: Bool { + let t = type.lowercased() + return ["integer", "bigint", "smallint", "real", "double precision", "money", "oid"].contains(t) || t.hasPrefix("numeric") + } +} + +public struct SQLRunResult: Codable, Sendable, Equatable { + public var statement: String + public var command: String + public var columns: [SQLRunColumn] + public var rows: [[String?]] + public var rowCount: Int + public var truncated: Bool + public var elapsedMS: Double + enum CodingKeys: String, CodingKey { + case statement, command, columns, rows, rowCount = "row_count", truncated, elapsedMS = "elapsed_ms" + } + public init(statement: String, command: String, columns: [SQLRunColumn], rows: [[String?]], rowCount: Int, truncated: Bool, elapsedMS: Double) { + self.statement = statement; self.command = command; self.columns = columns; self.rows = rows + self.rowCount = rowCount; self.truncated = truncated; self.elapsedMS = elapsedMS + } +} + +public struct SQLRunError: Codable, Sendable, Equatable { + public var statementIndex: Int + public var statement: String? + public var message: String + public var sqlstate: String? + public var detail: String? + public var hint: String? + public var position: Int? + enum CodingKeys: String, CodingKey { case statementIndex = "statement_index", statement, message, sqlstate, detail, hint, position } + public init(statementIndex: Int = -1, statement: String? = nil, message: String, sqlstate: String? = nil, + detail: String? = nil, hint: String? = nil, position: Int? = nil) { + self.statementIndex = statementIndex; self.statement = statement; self.message = message + self.sqlstate = sqlstate; self.detail = detail; self.hint = hint; self.position = position + } + /// True when pgbot (not the server) refused the statement. + public var isRefusal: Bool { sqlstate == "PGBOT" } +} + +public struct SQLRunOutput: Codable, Sendable, Equatable { + public var readOnly: Bool + public var results: [SQLRunResult] + public var error: SQLRunError? + public var elapsedMS: Double + enum CodingKeys: String, CodingKey { case readOnly = "read_only", results, error, elapsedMS = "elapsed_ms" } + public init(readOnly: Bool = true, results: [SQLRunResult], error: SQLRunError?, elapsedMS: Double) { + self.readOnly = readOnly; self.results = results; self.error = error; self.elapsedMS = elapsedMS + } +} + +/// A psql exchange as stored in the conversation. +public struct PSQLResultPayload: Codable, Sendable, Equatable { + public var input: String + /// e.g. `List of relations` for meta-commands. + public var title: String? + public var output: SQLRunOutput + public var expanded: Bool + public init(input: String, title: String?, output: SQLRunOutput, expanded: Bool) { + self.input = input; self.title = title; self.output = output; self.expanded = expanded + } + + /// Tab-separated text for copy, search and export. + public var plainText: String { + var parts = [input] + for r in output.results { + if r.columns.isEmpty { parts.append(r.command); continue } + parts.append(r.columns.map(\.name).joined(separator: "\t")) + parts += r.rows.map { $0.map { $0 ?? "" }.joined(separator: "\t") } + } + if let e = output.error { parts.append("ERROR: \(e.message)") } + return parts.joined(separator: "\n") + } +} + +// MARK: - psql input handling + +public enum PSQLCommand: Equatable, Sendable { + /// Plain SQL, sent as typed. + case sql(String) + /// A meta-command translated to catalog SQL (run read-only like any other). + case meta(sql: String, title: String) + case toggleExpanded(Bool?) + case help + case quit + case unsupported(String, reason: String) +} + +public enum PSQL { + /// Parses one line of console input the way psql would. + public static func parse(_ raw: String) -> PSQLCommand { + let input = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard input.hasPrefix("\\") else { return .sql(input) } + let parts = input.dropFirst().split(separator: " ", maxSplits: 1).map(String.init) + let cmd = parts.first ?? "" + let arg = parts.count > 1 ? parts[1].trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: ";")) : "" + let plus = cmd.hasSuffix("+") + let base = plus ? String(cmd.dropLast()) : cmd + + switch base { + case "?", "h", "help": return .help + case "q", "quit": return .quit + case "x": + switch arg.lowercased() { case "on": return .toggleExpanded(true); case "off": return .toggleExpanded(false); default: return .toggleExpanded(nil) } + case "l", "list": return .meta(sql: listDatabases, title: "List of databases") + case "dn": return .meta(sql: listSchemas(pattern: arg), title: "List of schemas") + case "d" where !arg.isEmpty: return describe(arg, verbose: plus) + case "d": return .meta(sql: listRelations(kinds: ["r", "p", "v", "m", "S", "f"], pattern: arg, verbose: plus), title: "List of relations") + case "dt": return .meta(sql: listRelations(kinds: ["r", "p"], pattern: arg, verbose: plus), title: "List of tables") + case "dv": return .meta(sql: listRelations(kinds: ["v"], pattern: arg, verbose: plus), title: "List of views") + case "dm": return .meta(sql: listRelations(kinds: ["m"], pattern: arg, verbose: plus), title: "List of materialized views") + case "ds": return .meta(sql: listRelations(kinds: ["S"], pattern: arg, verbose: plus), title: "List of sequences") + case "di": return .meta(sql: listRelations(kinds: ["i", "I"], pattern: arg, verbose: plus), title: "List of indexes") + case "df": return .meta(sql: listFunctions(pattern: arg), title: "List of functions") + case "du", "dg": return .meta(sql: listRoles, title: "List of roles") + case "dx": return .meta(sql: listExtensions, title: "List of installed extensions") + case "conninfo": return .meta(sql: connInfo, title: "Connection") + case "c", "connect": + return .unsupported(input, reason: "Each database bot is one connection. Pick another database in the sidebar to switch.") + case "!", "o", "out", "i", "ir", "include", "w", "write", "copy", "g", "gexec", "gset", "e", "edit", "ef", "ev", "set", "unset", "password", "lo_import", "lo_export", "setenv", "cd": + return .unsupported(input, reason: "\\\(base) touches files, the shell or session state, which PGBot's read-only console doesn't allow.") + default: + return .unsupported(input, reason: "PGBot doesn't support \\\(base) yet. Type \\? for the commands it does.") + } + } + + /// psql semantics: a meta-command runs on Return; SQL runs once it ends + /// with a semicolon outside quotes, dollar-quotes and comments. + public static func isComplete(_ raw: String) -> Bool { + let s = raw.trimmingCharacters(in: .whitespacesAndNewlines) + if s.isEmpty { return false } + if s.hasPrefix("\\") { return true } + var last: Character? = nil + var i = s.startIndex + var quote: Character? = nil + var dollarTag: String? = nil + while i < s.endIndex { + let c = s[i] + if let tag = dollarTag { + if s[i...].hasPrefix(tag) { i = s.index(i, offsetBy: tag.count); dollarTag = nil; last = "$"; continue } + i = s.index(after: i); continue + } + if let q = quote { + if c == q { quote = nil; last = c } + i = s.index(after: i); continue + } + if c == "-", s[i...].hasPrefix("--") { + while i < s.endIndex && s[i] != "\n" { i = s.index(after: i) } + continue + } + if c == "/", s[i...].hasPrefix("/*") { + if let end = s[i...].range(of: "*/") { i = end.upperBound } else { return false } + continue + } + if c == "'" || c == "\"" { quote = c; i = s.index(after: i); continue } + if c == "$", let m = s[i...].firstMatch(of: #/^\$[A-Za-z_]*\$/#) { + dollarTag = String(m.output); i = s.index(i, offsetBy: m.output.count); continue + } + if !c.isWhitespace { last = c } + i = s.index(after: i) + } + return quote == nil && dollarTag == nil && last == ";" + } + + public static let helpText = """ + **PSQL mode** runs your SQL in a read-only transaction that's always rolled back. Queries and catalog lookups work; changes don't. + + End a statement with `;` and press Return to run it. Shift-Return adds a line, ↑ and ↓ walk your history. + + | Command | Shows | + |---|---| + | `\\d name` | a table's columns and indexes | + | `\\d`, `\\dt`, `\\dv`, `\\dm`, `\\di`, `\\ds` | relations, tables, views, materialized views, indexes, sequences (add `+` for sizes) | + | `\\dn`, `\\df`, `\\dx` | schemas, functions, extensions | + | `\\l`, `\\du` | databases, roles | + | `\\conninfo` | who and where you're connected | + | `\\x` | expanded (one row per record) display | + | `\\q` | back to chat | + + Patterns work like psql: `\\dt public.order*`. + """ + + // MARK: Pattern → SQL (psql's rules, safely quoted) + + /// Converts a psql pattern to (schema regex?, name regex). `*` → `.*`, + /// `?` → `.`, unquoted text folds to lower case, double quotes keep case. + static func regexParts(_ pattern: String) -> (schema: String?, name: String)? { + guard !pattern.isEmpty else { return nil } + var parts: [String] = [""] + var inQuotes = false + for c in pattern { + switch c { + case "\"": inQuotes.toggle() + case "." where !inQuotes: parts.append("") + case "*" where !inQuotes: parts[parts.count - 1] += ".*" + case "?" where !inQuotes: parts[parts.count - 1] += "." + default: + let ch = inQuotes ? String(c) : String(c).lowercased() + parts[parts.count - 1] += "\\^$.|+()[]{}".contains(c) ? "\\" + ch : ch + } + } + let rx = parts.map { "^(" + $0 + ")$" } + return rx.count >= 2 ? (rx[rx.count - 2], rx[rx.count - 1]) : (nil, rx[0]) + } + + /// A single-quoted SQL literal with embedded quotes doubled. + static func literal(_ s: String) -> String { "'" + s.replacingOccurrences(of: "'", with: "''") + "'" } + + static func patternCondition(_ pattern: String, schema: String, name: String, visible: String) -> String { + guard let p = regexParts(pattern) else { + return "\(schema) NOT IN ('pg_catalog', 'information_schema') AND \(schema) !~ '^pg_toast'" + } + if let s = p.schema { return "\(schema) ~ \(literal(s)) AND \(name) ~ \(literal(p.name))" } + return "\(name) ~ \(literal(p.name)) AND \(visible)" + } + + static let relkindLabel = """ + CASE c.relkind WHEN 'r' THEN 'table' WHEN 'p' THEN 'partitioned table' WHEN 'v' THEN 'view' \ + WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'I' THEN 'partitioned index' \ + WHEN 'S' THEN 'sequence' WHEN 'f' THEN 'foreign table' END + """ + + static func listRelations(kinds: [String], pattern: String, verbose: Bool) -> String { + let inList = kinds.map { "'\($0)'" }.joined(separator: ", ") + let indexTable = kinds.contains("i") ? ", (SELECT t.relname FROM pg_index x JOIN pg_class t ON t.oid = x.indrelid WHERE x.indexrelid = c.oid) AS \"Table\"" : "" + let extra = verbose ? ", pg_size_pretty(pg_total_relation_size(c.oid)) AS \"Size\", obj_description(c.oid, 'pg_class') AS \"Description\"" : "" + return """ + SELECT n.nspname AS "Schema", c.relname AS "Name", \(relkindLabel) AS "Type", pg_get_userbyid(c.relowner) AS "Owner"\(indexTable)\(extra) + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE c.relkind IN (\(inList)) AND \(patternCondition(pattern, schema: "n.nspname", name: "c.relname", visible: "pg_table_is_visible(c.oid)")) + ORDER BY 1, 2; + """ + } + + static func describe(_ pattern: String, verbose: Bool) -> PSQLCommand { + guard let p = regexParts(pattern) else { return .unsupported("\\d", reason: "Give a table name, e.g. \\d orders") } + let match = p.schema.map { "n.nspname ~ \(literal($0)) AND c.relname ~ \(literal(p.name))" } + ?? "c.relname ~ \(literal(p.name))" + let target = """ + (SELECT c.oid FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \ + WHERE \(match) ORDER BY pg_table_is_visible(c.oid) DESC, n.nspname LIMIT 1) + """ + let columns = """ + SELECT a.attname AS "Column", format_type(a.atttypid, a.atttypmod) AS "Type", + CASE WHEN a.attnotnull THEN 'not null' ELSE '' END AS "Nullable", + coalesce(pg_get_expr(d.adbin, d.adrelid), '') AS "Default" + FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE a.attrelid = \(target) AND a.attnum > 0 AND NOT a.attisdropped + ORDER BY a.attnum; + """ + let indexes = """ + SELECT i.relname AS "Index", pg_get_indexdef(i.oid) AS "Definition"\(verbose ? ", pg_size_pretty(pg_relation_size(i.oid)) AS \"Size\"" : "") + FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid + WHERE x.indrelid = \(target) + ORDER BY 1; + """ + return .meta(sql: columns + "\n" + indexes, title: "Table \(pattern)") + } + + static func listSchemas(pattern: String) -> String { + let cond = regexParts(pattern).map { "n.nspname ~ \(literal($0.name))" } ?? "n.nspname !~ '^pg_' AND n.nspname <> 'information_schema'" + return "SELECT n.nspname AS \"Name\", pg_get_userbyid(n.nspowner) AS \"Owner\" FROM pg_namespace n WHERE \(cond) ORDER BY 1;" + } + + static func listFunctions(pattern: String) -> String { + """ + SELECT n.nspname AS "Schema", p.proname AS "Name", pg_get_function_result(p.oid) AS "Result data type", + pg_get_function_arguments(p.oid) AS "Argument data types", + CASE p.prokind WHEN 'a' THEN 'agg' WHEN 'w' THEN 'window' WHEN 'p' THEN 'proc' ELSE 'func' END AS "Type" + FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE \(patternCondition(pattern, schema: "n.nspname", name: "p.proname", visible: "pg_function_is_visible(p.oid)")) + ORDER BY 1, 2, 4; + """ + } + + static let listDatabases = """ + SELECT d.datname AS "Name", pg_get_userbyid(d.datdba) AS "Owner", pg_encoding_to_char(d.encoding) AS "Encoding", + CASE WHEN has_database_privilege(d.datname, 'CONNECT') THEN pg_size_pretty(pg_database_size(d.datname)) ELSE 'No Access' END AS "Size" + FROM pg_database d WHERE NOT d.datistemplate ORDER BY 1; + """ + + static let listRoles = """ + SELECT r.rolname AS "Role name", + concat_ws(', ', CASE WHEN r.rolsuper THEN 'Superuser' END, CASE WHEN r.rolcreaterole THEN 'Create role' END, + CASE WHEN r.rolcreatedb THEN 'Create DB' END, CASE WHEN NOT r.rolcanlogin THEN 'Cannot login' END, + CASE WHEN r.rolreplication THEN 'Replication' END, CASE WHEN r.rolbypassrls THEN 'Bypass RLS' END) AS "Attributes", + ARRAY(SELECT b.rolname FROM pg_auth_members m JOIN pg_roles b ON m.roleid = b.oid WHERE m.member = r.oid ORDER BY 1)::text AS "Member of" + FROM pg_roles r WHERE r.rolname !~ '^pg_' ORDER BY 1; + """ + + static let listExtensions = """ + SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", obj_description(e.oid, 'pg_extension') AS "Description" + FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace ORDER BY 1; + """ + + static let connInfo = """ + SELECT current_database() AS "Database", current_user AS "User", + coalesce(host(inet_server_addr()), 'local socket') AS "Server", coalesce(inet_server_port()::text, '') AS "Port", + current_setting('server_version') AS "Version", current_setting('transaction_read_only') AS "Read only"; + """ +} diff --git a/desktop/macos/Sources/PGBotKit/Persistence/Store.swift b/desktop/macos/Sources/PGBotKit/Persistence/Store.swift new file mode 100644 index 0000000..2649048 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Persistence/Store.swift @@ -0,0 +1,235 @@ +import Foundation +import SQLite3 + +/// Local-first persistence in one SQLite file (WAL mode). Rows are JSON +/// documents keyed and indexed by the columns the app filters on. No model +/// stored here has a password field — secrets live only in the Keychain. +public final class Store: @unchecked Sendable { + public enum StoreError: LocalizedError { + case open(String), sql(String) + public var errorDescription: String? { + switch self { case .open(let m): "Couldn't open local data: \(m)"; case .sql(let m): "Local data error: \(m)" } + } + } + + private var db: OpaquePointer? + private let lock = NSRecursiveLock() + private let encoder = EngineJSON.encoder() + private let decoder = EngineJSON.decoder() + public let url: URL? + + /// `nil` url = in-memory (checks, demo previews). + public init(url: URL?) throws { + self.url = url + if let url { try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) } + let path = url?.path ?? ":memory:" + guard sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK else { + throw StoreError.open(String(cString: sqlite3_errmsg(db))) + } + if let url { try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) } + try migrate() + } + + deinit { sqlite3_close(db) } + + private func migrate() throws { + try exec(""" + PRAGMA journal_mode=WAL; + PRAGMA foreign_keys=ON; + CREATE TABLE IF NOT EXISTS bots(id TEXT PRIMARY KEY, json TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS messages(id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, created_at REAL NOT NULL, json TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS messages_bot ON messages(bot_id, created_at); + CREATE TABLE IF NOT EXISTS inspections(id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, finished_at REAL NOT NULL, json TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS inspections_bot ON inspections(bot_id, finished_at); + CREATE TABLE IF NOT EXISTS samples(bot_id TEXT NOT NULL, metric TEXT NOT NULL, at REAL NOT NULL, value REAL NOT NULL); + CREATE INDEX IF NOT EXISTS samples_bot ON samples(bot_id, metric, at); + CREATE TABLE IF NOT EXISTS notifications(id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, created_at REAL NOT NULL, read INTEGER NOT NULL, json TEXT NOT NULL); + CREATE INDEX IF NOT EXISTS notifications_time ON notifications(created_at); + CREATE TABLE IF NOT EXISTS kv(key TEXT PRIMARY KEY, value TEXT NOT NULL); + """) + } + + // MARK: Bots + + public func saveBot(_ bot: DatabaseBot) throws { + try run("INSERT INTO bots(id,json) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET json=excluded.json", + [bot.id.uuidString, try json(bot)]) + } + + public func bots() throws -> [DatabaseBot] { + try query("SELECT json FROM bots", []) { try decode(DatabaseBot.self, $0.text(0)) } + .sorted { ($0.sortOrder, $0.createdAt) < ($1.sortOrder, $1.createdAt) } + } + + /// Removes a bot and everything that belongs to it. + public func deleteBot(_ id: UUID) throws { + try transaction { + for table in ["messages", "inspections", "samples", "notifications"] { + try run("DELETE FROM \(table) WHERE bot_id=?", [id.uuidString]) + } + try run("DELETE FROM bots WHERE id=?", [id.uuidString]) + } + } + + // MARK: Conversation + + public func append(_ m: ChatMessage) throws { + try run("INSERT OR REPLACE INTO messages(id,bot_id,created_at,json) VALUES(?,?,?,?)", + [m.id.uuidString, m.botID.uuidString, m.createdAt.timeIntervalSince1970, try json(m)]) + } + + public func deleteMessage(_ id: UUID) throws { try run("DELETE FROM messages WHERE id=?", [id.uuidString]) } + + public func messages(for botID: UUID, limit: Int = 500) throws -> [ChatMessage] { + try query("SELECT json FROM (SELECT json, created_at FROM messages WHERE bot_id=? ORDER BY created_at DESC LIMIT ?) ORDER BY created_at ASC", + [botID.uuidString, limit]) { try decode(ChatMessage.self, $0.text(0)) } + } + + public func clearConversation(_ botID: UUID) throws { try run("DELETE FROM messages WHERE bot_id=?", [botID.uuidString]) } + + // MARK: Inspections & metrics + + public func save(_ r: InspectionRecord) throws { + try transaction { + try run("INSERT OR REPLACE INTO inspections(id,bot_id,finished_at,json) VALUES(?,?,?,?)", + [r.id.uuidString, r.botID.uuidString, r.finishedAt.timeIntervalSince1970, try json(r)]) + for s in MetricKey.samples(from: r) { + try run("INSERT INTO samples(bot_id,metric,at,value) VALUES(?,?,?,?)", + [s.botID.uuidString, s.metric.rawValue, s.at.timeIntervalSince1970, s.value]) + } + } + } + + public func latestInspection(for botID: UUID) throws -> InspectionRecord? { + try inspections(for: botID, limit: 1).first + } + + public func inspections(for botID: UUID, limit: Int) throws -> [InspectionRecord] { + try query("SELECT json FROM inspections WHERE bot_id=? ORDER BY finished_at DESC LIMIT ?", [botID.uuidString, limit]) { + try decode(InspectionRecord.self, $0.text(0)) + } + } + + public func samples(for botID: UUID, metric: MetricKey, since: Date) throws -> [MetricPoint] { + try query("SELECT at,value FROM samples WHERE bot_id=? AND metric=? AND at>=? ORDER BY at", + [botID.uuidString, metric.rawValue, since.timeIntervalSince1970]) { + MetricPoint(at: Date(timeIntervalSince1970: $0.double(0)), value: $0.double(1)) + } + } + + /// Bulk insert for demo history. + public func insertSamples(_ s: [MetricSample]) throws { + try transaction { + for x in s { + try run("INSERT INTO samples(bot_id,metric,at,value) VALUES(?,?,?,?)", + [x.botID.uuidString, x.metric.rawValue, x.at.timeIntervalSince1970, x.value]) + } + } + } + + /// Drops history older than each bot's retention. + public func prune(botID: UUID, olderThan cutoff: Date) throws { + let t = cutoff.timeIntervalSince1970, id = botID.uuidString + try transaction { + try run("DELETE FROM samples WHERE bot_id=? AND at [AppNotification] { + try query("SELECT json FROM notifications ORDER BY created_at DESC LIMIT ?", [limit]) { + try decode(AppNotification.self, $0.text(0)) + } + } + + // MARK: Key-value settings + + public func setValue(_ v: T, for key: String) throws { + try run("INSERT INTO kv(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", [key, try json(v)]) + } + + public func value(_ type: T.Type, for key: String) -> T? { + (try? query("SELECT value FROM kv WHERE key=?", [key]) { try decode(T.self, $0.text(0)) })?.first + } + + /// The stored JSON for a key, for callers that merge it with newer defaults. + public func rawValue(for key: String) -> Data? { + (try? query("SELECT value FROM kv WHERE key=?", [key]) { Data($0.text(0).utf8) })?.first + } + + public func wipe() throws { + try exec("DELETE FROM bots; DELETE FROM messages; DELETE FROM inspections; DELETE FROM samples; DELETE FROM notifications; DELETE FROM kv;") + } + + // MARK: - SQLite plumbing + + private func json(_ v: T) throws -> String { String(decoding: try encoder.encode(v), as: UTF8.self) } + private func decode(_ t: T.Type, _ s: String) throws -> T { try decoder.decode(t, from: Data(s.utf8)) } + + private func exec(_ sql: String) throws { + lock.lock(); defer { lock.unlock() } + var err: UnsafeMutablePointer? + if sqlite3_exec(db, sql, nil, nil, &err) != SQLITE_OK { + let m = err.map { String(cString: $0) } ?? "unknown"; sqlite3_free(err) + throw StoreError.sql(m) + } + } + + private func transaction(_ body: () throws -> Void) throws { + lock.lock(); defer { lock.unlock() } + try exec("BEGIN IMMEDIATE") + do { try body(); try exec("COMMIT") } catch { try? exec("ROLLBACK"); throw error } + } + + struct Row { + let stmt: OpaquePointer + func text(_ i: Int32) -> String { sqlite3_column_text(stmt, i).map { String(cString: $0) } ?? "" } + func double(_ i: Int32) -> Double { sqlite3_column_double(stmt, i) } + } + + private static let transient = unsafeBitCast(-1, to: sqlite3_destructor_type.self) + + private func prepare(_ sql: String, _ args: [Any]) throws -> OpaquePointer { + var stmt: OpaquePointer? + guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let s = stmt else { + throw StoreError.sql(String(cString: sqlite3_errmsg(db))) + } + for (i, a) in args.enumerated() { + let idx = Int32(i + 1) + switch a { + case let v as String: sqlite3_bind_text(s, idx, v, -1, Self.transient) + case let v as Int: sqlite3_bind_int64(s, idx, Int64(v)) + case let v as Double: sqlite3_bind_double(s, idx, v) + default: sqlite3_bind_null(s, idx) + } + } + return s + } + + private func run(_ sql: String, _ args: [Any]) throws { + lock.lock(); defer { lock.unlock() } + let s = try prepare(sql, args) + defer { sqlite3_finalize(s) } + guard sqlite3_step(s) == SQLITE_DONE else { throw StoreError.sql(String(cString: sqlite3_errmsg(db))) } + } + + private func query(_ sql: String, _ args: [Any], _ map: (Row) throws -> T) throws -> [T] { + lock.lock(); defer { lock.unlock() } + let s = try prepare(sql, args) + defer { sqlite3_finalize(s) } + var out: [T] = [] + while sqlite3_step(s) == SQLITE_ROW { out.append(try map(Row(stmt: s))) } + return out + } +} diff --git a/desktop/macos/Sources/PGBotKit/Security/ConnectionString.swift b/desktop/macos/Sources/PGBotKit/Security/ConnectionString.swift new file mode 100644 index 0000000..ee66b36 --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Security/ConnectionString.swift @@ -0,0 +1,73 @@ +import Foundation + +/// Parses a pasted `postgres://` URL into non-secret settings plus the secret, +/// and rebuilds a DSN for the engine. The DSN only ever travels to the engine +/// through its environment (`PGBOT_DATABASE_URL`), never argv, a file, or a log. +public enum ConnectionString { + public struct Parsed: Equatable, Sendable { + public var connection: DatabaseConnection + public var password: String? + } + + public enum ParseError: LocalizedError, Equatable { + case notAURL, unsupportedScheme(String), missingHost + public var errorDescription: String? { + switch self { + case .notAURL: "That doesn't look like a connection URL. It should start with postgresql://" + case .unsupportedScheme(let s): "“\(s)://” isn't a PostgreSQL URL. Use postgresql:// or postgres://" + case .missingHost: "The URL has no host name." + } + } + } + + public static func parse(_ raw: String) throws -> Parsed { + let s = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard let comps = URLComponents(string: s), let scheme = comps.scheme?.lowercased() else { throw ParseError.notAURL } + guard scheme == "postgres" || scheme == "postgresql" else { throw ParseError.unsupportedScheme(scheme) } + guard let host = comps.host, !host.isEmpty else { throw ParseError.missingHost } + // URLComponents' plain accessors (host, user, password, path) are already + // percent-decoded — decoding again would corrupt a password containing "%". + let path = String(comps.path.dropFirst()) + var conn = DatabaseConnection( + host: host, + port: comps.port ?? 5432, + database: path.isEmpty ? "postgres" : path, + username: comps.user.flatMap { $0.isEmpty ? nil : $0 } ?? "postgres") + for item in comps.queryItems ?? [] { + guard let v = item.value else { continue } + switch item.name { + case "sslmode": conn.sslMode = SSLMode(rawValue: v) ?? conn.sslMode + case "connect_timeout": conn.connectTimeoutSeconds = Int(v) ?? conn.connectTimeoutSeconds + case "password": continue // a secret in the query string goes to the Keychain, not settings + default: conn.extraParameters[item.name] = v + } + } + var password = comps.password + if password == nil, let q = comps.queryItems?.first(where: { $0.name == "password" })?.value { password = q } + return Parsed(connection: conn, password: password) + } + + /// Builds the DSN handed to the engine. Callers must treat the result as a secret. + public static func build(_ c: DatabaseConnection, password: String?) -> String { + var comps = URLComponents() + comps.scheme = "postgresql" + comps.host = c.host + comps.port = c.port + comps.percentEncodedUser = encode(c.username) + if let p = password, !p.isEmpty { comps.percentEncodedPassword = encode(p) } + comps.percentEncodedPath = "/" + encode(c.database) + var items = [URLQueryItem(name: "sslmode", value: c.sslMode.rawValue), + URLQueryItem(name: "connect_timeout", value: String(c.connectTimeoutSeconds))] + items += c.extraParameters.sorted(by: { $0.key < $1.key }).map { URLQueryItem(name: $0.key, value: $0.value) } + comps.queryItems = items + return comps.string ?? "" + } + + /// RFC 3986 unreserved characters only — everything else is escaped so + /// `@`, `:`, `/`, `?`, `#` in passwords can't break the URL. + private static func encode(_ s: String) -> String { + var allowed = CharacterSet.alphanumerics + allowed.insert(charactersIn: "-._~") + return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s + } +} diff --git a/desktop/macos/Sources/PGBotKit/Security/Keychain.swift b/desktop/macos/Sources/PGBotKit/Security/Keychain.swift new file mode 100644 index 0000000..19e96df --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Security/Keychain.swift @@ -0,0 +1,82 @@ +import Foundation +import Security + +/// Secrets storage. Production uses the macOS Keychain; checks use the in-memory store. +public protocol SecretStore: Sendable { + func set(_ secret: String, for account: String) throws + func get(_ account: String) throws -> String? + func delete(_ account: String) throws +} + +public enum KeychainError: LocalizedError, Equatable { + case unexpected(OSStatus) + public var errorDescription: String? { + switch self { + case .unexpected(let s): + let msg = SecCopyErrorMessageString(s, nil) as String? ?? "status \(s)" + return "Keychain error: \(msg)" + } + } +} + +/// Generic-password items under one service. Items are device-only +/// (`…ThisDeviceOnly`) so database credentials never sync to iCloud Keychain, +/// and are readable only after first unlock — background monitoring needs them +/// while the screen is locked, but never before the user has logged in. +public struct KeychainStore: SecretStore { + public let service: String + public init(service: String = "dev.pgbot.desktop") { self.service = service } + + private func base(_ account: String) -> [String: Any] { + [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account] + } + + public func set(_ secret: String, for account: String) throws { + let data = Data(secret.utf8) + let update: [String: Any] = [kSecValueData as String: data, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] + var status = SecItemUpdate(base(account) as CFDictionary, update as CFDictionary) + if status == errSecItemNotFound { + var add = base(account) + add.merge(update) { $1 } + add[kSecAttrLabel as String] = "PGBot — \(account.split(separator: ":").first ?? "secret")" + status = SecItemAdd(add as CFDictionary, nil) + } + guard status == errSecSuccess else { throw KeychainError.unexpected(status) } + } + + public func get(_ account: String) throws -> String? { + var q = base(account) + q[kSecReturnData as String] = true + q[kSecMatchLimit as String] = kSecMatchLimitOne + var out: CFTypeRef? + let status = SecItemCopyMatching(q as CFDictionary, &out) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess, let data = out as? Data else { throw KeychainError.unexpected(status) } + return String(data: data, encoding: .utf8) + } + + public func delete(_ account: String) throws { + let status = SecItemDelete(base(account) as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError.unexpected(status) } + } +} + +public final class InMemorySecretStore: SecretStore, @unchecked Sendable { + private var items: [String: String] = [:] + private let lock = NSLock() + public init() {} + public func set(_ secret: String, for account: String) throws { lock.withLock { items[account] = secret } } + public func get(_ account: String) throws -> String? { lock.withLock { items[account] } } + public func delete(_ account: String) throws { _ = lock.withLock { items.removeValue(forKey: account) } } + public var count: Int { lock.withLock { items.count } } +} + +/// Well-known Keychain account names, so every caller agrees. +public enum SecretAccount { + public static func database(_ id: UUID) -> String { "db:\(id.uuidString)" } + public static func aiKey(_ provider: AIProviderKind) -> String { "ai:\(provider.rawValue)" } + public static let authSession = "auth:session" +} diff --git a/desktop/macos/Sources/PGBotKit/Security/Redactor.swift b/desktop/macos/Sources/PGBotKit/Security/Redactor.swift new file mode 100644 index 0000000..0705cbf --- /dev/null +++ b/desktop/macos/Sources/PGBotKit/Security/Redactor.swift @@ -0,0 +1,47 @@ +import Foundation + +/// Last-line redaction for anything the app displays, persists, or sends to an +/// AI provider that did not already go through the engine's own scrubbing. +/// The engine scrubs SQL literals in its JSON (`--json` is the scrubbed +/// contract); this covers engine *stderr* (which can echo a DSN), pasted text, +/// and log lines the user hands to "Explain with PGBot". +public enum Redactor { + private static let rules: [(NSRegularExpression, String)] = [ + // user:password@ inside any URL-ish DSN + (re(#"(?i)\b(postgres(?:ql)?|mysql|redis|https?)://([^:/@\s]+):([^@\s]+)@"#), "$1://$2:•••@"), + // key=value secrets in libpq keyword DSNs and env dumps + (re(#"(?i)\b(password|passwd|pwd|sslpassword|api[_-]?key|secret|token)\s*=\s*('[^']*'|"[^"]*"|\S+)"#), "$1=•••"), + // Authorization headers / bearer tokens + (re(#"(?i)\b(bearer)\s+[A-Za-z0-9\-._~+/]{12,}=*"#), "$1 •••"), + // Common provider key shapes (sk-…, xai-…, AIza…, ghp_…) + (re(#"\b(sk-(?:ant-)?[A-Za-z0-9\-_]{16,}|xai-[A-Za-z0-9]{16,}|AIza[0-9A-Za-z\-_]{30,}|gh[pousr]_[A-Za-z0-9]{30,})\b"#), "•••"), + // E-mail addresses + (re(#"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}"#), ""), + ] + + /// SQL string literals and numeric literals → placeholders, as the engine does. + private static let sqlLiteral = re(#"'(?:[^']|'')*'"#) + private static let sqlNumber = re(#"(? String { + rules.reduce(s) { acc, rule in + rule.0.stringByReplacingMatches(in: acc, range: NSRange(acc.startIndex..., in: acc), withTemplate: rule.1) + } + } + + /// Redacts secrets and also SQL literals — for log lines and SQL before AI. + public static func redactSQLLiterals(_ s: String) -> String { + var out = redact(s) + out = sqlLiteral.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: "'?'") + out = sqlNumber.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: "?") + return out + } + + /// Removes one specific secret wherever it appears (e.g. the bot's own + /// password echoed back by a driver error). + public static func scrub(_ s: String, secrets: [String]) -> String { + secrets.filter { $0.count >= 3 }.reduce(redact(s)) { $0.replacingOccurrences(of: $1, with: "•••") } + } + + private static func re(_ p: String) -> NSRegularExpression { try! NSRegularExpression(pattern: p) } +} diff --git a/desktop/macos/Tests/PGBotKitChecks/main.swift b/desktop/macos/Tests/PGBotKitChecks/main.swift new file mode 100644 index 0000000..93ce85e --- /dev/null +++ b/desktop/macos/Tests/PGBotKitChecks/main.swift @@ -0,0 +1,636 @@ +// PGBotKit check suite. +// +// Command Line Tools ship without XCTest, so this is a self-contained runner: +// swift run PGBotKitChecks # unit checks +// PGBOT_TEST_DSN=postgres://… PGBOT_ENGINE_PATH=../../bin/pgbot swift run PGBotKitChecks +// # + live engine integration +// Exit status is non-zero if any check fails. +import Foundation +import PGBotKit + +nonisolated(unsafe) var failures: [String] = [] +nonisolated(unsafe) var passed = 0 +nonisolated(unsafe) var current = "" + +func expect(_ cond: @autoclosure () -> Bool, _ msg: String = "", file: StaticString = #fileID, line: UInt = #line) { + if !cond() { failures.append("\(current): \(msg) (\(file):\(line))") } +} +func expectEq(_ a: T, _ b: T, _ msg: String = "", file: StaticString = #fileID, line: UInt = #line) { + if a != b { failures.append("\(current): \(msg) — got \(a), want \(b) (\(file):\(line))") } +} +func check(_ name: String, _ body: () throws -> Void) { + current = name; let before = failures.count + do { try body() } catch { failures.append("\(name): threw \(error)") } + if failures.count == before { passed += 1; print(" ✓ \(name)") } else { print(" ✗ \(name)") } +} +func checkAsync(_ name: String, _ body: () async throws -> Void) async { + current = name; let before = failures.count + do { try await body() } catch { failures.append("\(name): threw \(error)") } + if failures.count == before { passed += 1; print(" ✓ \(name)") } else { print(" ✗ \(name)") } +} + +func finding(_ id: String, _ sev: Severity, object: String? = nil, title: String? = nil, suppressed: Bool = false) -> Finding { + Finding(id: id, object: object, severity: sev, title: title ?? id, detail: "", suppressed: suppressed) +} + +let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("pgbot-checks-\(UUID().uuidString)") +try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true) +defer { try? FileManager.default.removeItem(at: scratch) } + +// MARK: - Health score + +print("Health score") +check("engine formula: 10 per critical, 3 per warning, 1 per info") { + expectEq(HealthScore.engineScore([]), 100) + expectEq(HealthScore.engineScore([finding("a", .critical), finding("b", .warn), finding("c", .info)]), 86) + expectEq(HealthScore.engineScore([finding("a", .warn), finding("b", .warn)]), 94) +} +check("suppressed findings don't count; floor at zero") { + expectEq(HealthScore.engineScore([finding("a", .critical, suppressed: true)]), 100) + expectEq(HealthScore.engineScore((0..<15).map { finding("c\($0)", .critical) }), 0) +} +check("demo hero bot scores 94 from two real-shaped warnings") { + let d = DemoData.make() + expectEq(d.records[0].score.value, 94) + expectEq(d.records[0].score.warnings, 2) + expectEq(d.records[0].score.critical, 0) + expect(d.bots.allSatisfy(\.isDemo), "every demo bot must be flagged isDemo") +} +check("unavailable sections make the grade partial or unavailable, never silently healthy") { + let base = String(decoding: DemoData.contextJSONForChecks(), as: UTF8.self) + let partial = base.replacingOccurrences(of: #""queries":{"exactness":"cumulative""#, with: #""queries":{"exactness":"unavailable","reason":"pg_stat_statements is not installed""#) + let p = HealthScore.from(try EngineJSON.decodeContext(Data(partial.utf8))) + expectEq(p.completeness, .partial) + expect(p.gaps.contains { $0.contains("pg_stat_statements") }, "gap carries the engine's reason") + let none = partial + .replacingOccurrences(of: #""health":{"exactness":"sampled""#, with: #""health":{"exactness":"unavailable""#) + .replacingOccurrences(of: #""activity":{"exactness":"scraped""#, with: #""activity":{"exactness":"unavailable""#) + let u = HealthScore.from(try EngineJSON.decodeContext(Data(none.utf8))) + expectEq(u.completeness, .unavailable) + expectEq(HealthBands().band(for: u), .gray) +} +check("bands: 90+ green, 70+ yellow, 50+ orange, else red") { + func s(_ v: Int) -> HealthScore { HealthScore(value: v, critical: 0, warnings: 0, info: 0, completeness: .complete, gaps: []) } + let b = HealthBands() + expectEq(b.band(for: s(94)), .green); expectEq(b.band(for: s(70)), .yellow) + expectEq(b.band(for: s(50)), .orange); expectEq(b.band(for: s(49)), .red) +} + +// MARK: - JSON contract + +print("Engine JSON") +check("decodes Go RFC 3339 timestamps with nanoseconds") { + let json = String(decoding: DemoData.contextJSONForChecks(), as: UTF8.self) + .replacing(#/"collected_at":"[^"]+"/#, with: #""collected_at":"2026-11-25T09:14:03.123456789+01:00""#) + let c = try EngineJSON.decodeContext(Data(json.utf8)) + expectEq(Int(c.collectedAt.timeIntervalSince1970), 1_795_594_443) // 2026-11-25T08:14:03Z +} +check("tolerates unknown keys and null findings (additive contract)") { + let json = #"{"schema_version":"1.9.0","collected_at":"2026-01-01T00:00:00Z","fingerprint":"x","server":{"version_num":170002,"version_text":"","database":"d","future_field":1},"findings":null,"brand_new_section":{"a":1}}"# + let c = try EngineJSON.decodeContext(Data(json.utf8)) + expectEq(c.findings.count, 0); expectEq(c.server.displayVersion, "PostgreSQL 17.2"); expectEq(c.schemaMajor, 1) +} +check("newline-delimited logs skip non-JSON lines") { + let data = Data(""" + {"time":"2026-01-01T00:00:00Z","severity":"ERROR","level":"error","message":"deadlock detected"} + not json + {"time":"2026-01-01T00:00:01.5Z","severity":"LOG","level":"info","message":"checkpoint"} + """.utf8) + let rows = EngineJSON.decodeLines(LogEntry.self, from: data) + expectEq(rows.count, 2); expectEq(rows[0].message, "deadlock detected") +} + +// MARK: - Connection strings & redaction + +print("Security") +check("parses a pasted URL; password goes out of band, never into settings") { + let p = try ConnectionString.parse("postgresql://app%40corp:s3cr%3At%2F@db.example.com:6543/shop?sslmode=require&application_name=x") + expectEq(p.connection.host, "db.example.com"); expectEq(p.connection.port, 6543) + expectEq(p.connection.username, "app@corp"); expectEq(p.connection.database, "shop") + expectEq(p.connection.sslMode, .require); expectEq(p.password, "s3cr:t/") + expectEq(p.connection.extraParameters["application_name"], "x") + let encoded = String(decoding: try JSONEncoder().encode(p.connection), as: UTF8.self) + expect(!encoded.contains("s3cr"), "settings JSON must not contain the password") +} +check("password in the query string is treated as a secret too") { + let p = try ConnectionString.parse("postgres://u@h/db?password=hunter22") + expectEq(p.password, "hunter22"); expect(p.connection.extraParameters["password"] == nil) +} +check("build round-trips awkward passwords") { + let c = DatabaseConnection(host: "h", port: 5432, database: "my db", username: "u:x", sslMode: .verifyFull) + let pw = "p@ss:w/rd?#%&=" + let back = try ConnectionString.parse(ConnectionString.build(c, password: pw)) + expectEq(back.password, pw); expectEq(back.connection.username, "u:x"); expectEq(back.connection.database, "my db") + expectEq(back.connection.sslMode, .verifyFull) +} +check("rejects non-Postgres URLs with a helpful message") { + do { _ = try ConnectionString.parse("mysql://h/db"); expect(false, "should throw") } + catch let e as ConnectionString.ParseError { expectEq(e, .unsupportedScheme("mysql")) } +} +check("redacts DSN passwords, key=value secrets, provider keys, bearer tokens, emails") { + let s = Redactor.redact(""" + dial postgresql://admin:Sup3rS3cret@db:5432/x failed; password=abc123 api_key='zzz' \ + sk-ant-REDACTED Bearer eyJhbGciOiJIUzI1NiJ9.e30 user bob@example.com + """) + for leak in ["Sup3rS3cret", "abc123", "zzz", "sk-ant-api03", "eyJhbGci", "bob@example.com"] { + expect(!s.contains(leak), "leaked \(leak) in: \(s)") + } + expect(s.contains("admin:•••@db"), "keeps the user for context") +} +check("SQL literal redaction for AI-bound logs") { + let s = Redactor.redactSQLLiterals("SELECT * FROM users WHERE email = 'a@b.co' AND id = 42 AND t2.col = 'it''s'") + expect(!s.contains("a@b.co") && !s.contains("42") && !s.contains("it''s"), s) + expect(s.contains("t2.col"), "identifiers with digits survive: \(s)") +} +check("scrub removes an exact secret even if the patterns miss it") { + expectEq(Redactor.scrub("weird token tok3n-xyz here", secrets: ["tok3n-xyz"]), "weird token ••• here") +} +check("engine error classification gives actionable categories") { + func p(_ s: String) -> EngineError.ConnectionProblem? { if case .connection(let p, _) = EngineError.classify(stderr: s) { return p }; return nil } + expectEq(p("pgbot: failed to connect: FATAL: password authentication failed for user \"x\""), .authentication) + expectEq(p("dial tcp 10.0.0.1:5432: connect: connection refused"), .unreachable) + expectEq(p("tls: failed to verify certificate: x509: unknown authority"), .ssl) + expectEq(p("ERROR: permission denied for function pg_ls_waldir"), .permission) + expectEq(p(#"FATAL: database "nope" does not exist"#), .databaseMissing) + expectEq(p("context deadline exceeded"), .timeout) + // An unknown role is a credentials problem, not an unreachable server, even + // though the message starts with "connect:". + expectEq(p(#"pgbot: connect: connect to 127.0.0.1:5432: FATAL: role "ghost" does not exist (SQLSTATE 28000)"#), .authentication) + expectEq(p("connect: FATAL: password authentication failed for user \"x\" (SQLSTATE 28P01)"), .authentication) + expectEq(p(#"connect: FATAL: database "nope" does not exist (SQLSTATE 3D000)"#), .databaseMissing) +} + +// MARK: - Keychain + +print("Keychain") +check("in-memory store set/get/delete") { + let s = InMemorySecretStore() + try s.set("a", for: "db:1"); expectEq(try s.get("db:1"), "a") + try s.set("b", for: "db:1"); expectEq(try s.get("db:1"), "b") + try s.delete("db:1"); expectEq(try s.get("db:1"), nil) +} +if ProcessInfo.processInfo.environment["PGBOT_SKIP_KEYCHAIN"] == nil { + check("macOS Keychain round-trip (isolated service, cleaned up)") { + let k = KeychainStore(service: "dev.pgbot.desktop.checks.\(UUID().uuidString)") + defer { try? k.delete("db:check") } + try k.set("pässwörd", for: "db:check"); expectEq(try k.get("db:check"), "pässwörd") + try k.set("rotated", for: "db:check"); expectEq(try k.get("db:check"), "rotated") + try k.delete("db:check"); expectEq(try k.get("db:check"), nil) + try k.delete("db:check") // idempotent + } +} + +// MARK: - Finding diff & notifications + +print("Monitoring") +check("compare: new / escalated / de-escalated / resolved / unchanged by id+object") { + let prev = [finding("a", .warn, object: "t1"), finding("b", .critical), finding("c", .warn), finding("d", .info)] + let cur = [finding("a", .critical, object: "t1"), finding("b", .warn), finding("c", .warn, title: "renamed"), finding("e", .warn)] + let ch = FindingChanges.compare(previous: prev, current: cur) + expectEq(ch.escalated.map(\.id), ["a"]); expectEq(ch.deescalated.map(\.id), ["b"]) + expectEq(ch.unchanged.map(\.id), ["c"], "a title change is not a new finding") + expectEq(ch.new.map(\.id), ["e"]); expectEq(ch.resolved.map(\.id), ["d"]) +} +check("same id on a different object is a different finding") { + let ch = FindingChanges.compare(previous: [finding("bloat", .warn, object: "t1")], current: [finding("bloat", .warn, object: "t2")]) + expectEq(ch.new.count, 1); expectEq(ch.resolved.count, 1) +} +check("suppressed and user-ignored findings are invisible to the diff") { + let ch = FindingChanges.compare(previous: [], current: [finding("a", .critical, suppressed: true), finding("b", .warn)], ignoring: ["b"]) + expect(ch.isEmpty) +} +check("notification dedup: an unchanged finding is announced once across runs") { + var ledger = AnnouncementLedger() + let s = HealthScore(value: 97, critical: 0, warnings: 1, info: 0, completeness: .complete, gaps: []) + let f = finding("x", .warn) + let n1 = NotificationPlanner.plan(botName: "B", changes: FindingChanges.compare(previous: [], current: [f]), + scoreBefore: nil, scoreAfter: s, ledger: &ledger, prefs: .init()) + expectEq(n1.count, 1) + // A failed run in between loses `previous`: diff says "new" again, ledger says "already told them". + let n2 = NotificationPlanner.plan(botName: "B", changes: FindingChanges.compare(previous: [], current: [f]), + scoreBefore: nil, scoreAfter: s, ledger: &ledger, prefs: .init()) + expectEq(n2.count, 0) + // Escalation is news. + let n3 = NotificationPlanner.plan(botName: "B", changes: FindingChanges.compare(previous: [f], current: [finding("x", .critical)]), + scoreBefore: 97, scoreAfter: s, ledger: &ledger, prefs: .init()) + expectEq(n3.map(\.category), [.criticalFinding]) + // Resolution of an announced finding is news, once. + let n4 = NotificationPlanner.plan(botName: "B", changes: FindingChanges.compare(previous: [finding("x", .critical)], current: []), + scoreBefore: 90, scoreAfter: s, ledger: &ledger, prefs: .init()) + expectEq(n4.map(\.category), [.resolved]) +} +check("below-threshold findings and disabled categories stay quiet") { + var ledger = AnnouncementLedger() + let s = HealthScore(value: 99, critical: 0, warnings: 0, info: 1, completeness: .complete, gaps: []) + let n = NotificationPlanner.plan(botName: "B", changes: FindingChanges.compare(previous: [], current: [finding("i", .info), finding("w", .warn)]), + scoreBefore: nil, scoreAfter: s, ledger: &ledger, prefs: .init(minimum: .warn, disabled: [.warning])) + expect(n.isEmpty, "\(n)") +} +check("connectivity outage announced once, recovery announced once") { + var ledger = AnnouncementLedger() + let err = EngineError.connection(.unreachable, detail: "refused") + expect(NotificationPlanner.planFailure(botName: "B", error: err, ledger: &ledger, prefs: .init()) != nil) + expect(NotificationPlanner.planFailure(botName: "B", error: err, ledger: &ledger, prefs: .init()) == nil) + let s = HealthScore(value: 100, critical: 0, warnings: 0, info: 0, completeness: .complete, gaps: []) + let n = NotificationPlanner.plan(botName: "B", changes: .init(), scoreBefore: nil, scoreAfter: s, ledger: &ledger, prefs: .init()) + expectEq(n.map(\.dedupKey), ["connectivity|up"]) +} +check("quiet hours wrap midnight") { + var q = QuietHours(); q.enabled = true; q.startHour = 22; q.endHour = 7 + let cal = Calendar.current, d = Date() + expect(q.contains(cal.date(bySettingHour: 23, minute: 0, second: 0, of: d)!)) + expect(q.contains(cal.date(bySettingHour: 3, minute: 0, second: 0, of: d)!)) + expect(!q.contains(cal.date(bySettingHour: 12, minute: 0, second: 0, of: d)!)) +} + +// MARK: - Scheduler + +final class Clock: @unchecked Sendable { var now = Date(timeIntervalSince1970: 1_000_000) } +final class Calls: @unchecked Sendable { var ids: [UUID] = []; var outcome: InspectionScheduler.Outcome = .success; let lock = NSLock() } + +await checkAsync("scheduler: due order, pause, sleep/wake, per-bot intervals") { + let clock = Clock(), calls = Calls() + let s = InspectionScheduler(clock: { clock.now }) { id in calls.lock.withLock { calls.ids.append(id); return calls.outcome } } + let a = UUID(), b = UUID(), c = UUID() + await s.register(a, interval: 60, paused: false, firstRunAt: clock.now) + await s.register(b, interval: 3600, paused: false, firstRunAt: clock.now.addingTimeInterval(-10)) + await s.register(c, interval: 60, paused: true, firstRunAt: clock.now) + expectEq(await s.dueIDs(), [b, a], "oldest-due first, paused excluded") + await s.runDue() + expectEq(Set(calls.ids), [a, b]) + expectEq(await s.dueIDs(), []) + clock.now += 61 + expectEq(await s.dueIDs(), [a], "a's 60s interval elapsed, b's hour hasn't") + await s.willSleep(); expectEq(await s.dueIDs(), [], "nothing runs while asleep") + await s.didWake(); expectEq(await s.dueIDs(), [a], "overdue work runs once on wake") + await s.setGloballyPaused(true); expectEq(await s.dueIDs(), []) +} +await checkAsync("scheduler: failures back off exponentially, success resets") { + let clock = Clock(), calls = Calls(); calls.outcome = .failure + let s = InspectionScheduler(clock: { clock.now }) { _ in calls.outcome } + let a = UUID() + await s.register(a, interval: 3600, paused: false, firstRunAt: clock.now) + await s.runDue() + expectEq(await s.entry(a)!.nextDue.timeIntervalSince(clock.now), 60) + clock.now += 60; await s.runDue() + expectEq(await s.entry(a)!.nextDue.timeIntervalSince(clock.now), 120) + expectEq(await s.entry(a)!.consecutiveFailures, 2) + calls.outcome = .success; clock.now += 120; await s.runDue() + expectEq(await s.entry(a)!.consecutiveFailures, 0) + expectEq(await s.entry(a)!.nextDue.timeIntervalSince(clock.now), 3600) + expectEq(InspectionScheduler.backoff(failures: 10, interval: 900, cap: 21600), 900, "never slower than the healthy interval") +} + +// MARK: - Persistence + +print("Persistence") +check("bots, conversations, inspections and metrics round-trip through SQLite") { + let url = scratch.appendingPathComponent("store.sqlite") + let demo = DemoData.make() + do { + let s = try Store(url: url) + for b in demo.bots { try s.saveBot(b) } + for m in demo.messages { try s.append(m) } + for r in demo.records { try s.save(r) } + } + let s = try Store(url: url) // reopen: persistence, not memory + expectEq(try s.bots().map(\.displayName), demo.bots.map(\.displayName)) + let hero = demo.bots[0].id + let msgs = try s.messages(for: hero) + expectEq(msgs.count, demo.messages.filter { $0.botID == hero }.count) + expect(msgs.map(\.createdAt) == msgs.map(\.createdAt).sorted(), "chronological") + let other = try s.messages(for: demo.bots[1].id) + expect(other.allSatisfy { $0.botID == demo.bots[1].id }, "conversations are per-bot") + expectEq(try s.latestInspection(for: hero)?.score.value, 94) + let tps = try s.samples(for: hero, metric: .tps, since: .distantPast) + expect(!tps.isEmpty, "inspection writes metric samples") + try s.deleteBot(hero) + expectEq(try s.messages(for: hero).count, 0) + let gone = try s.latestInspection(for: hero) + expect(gone == nil, "inspections removed with the bot") + expectEq(try s.bots().count, demo.bots.count - 1) +} +check("no password ever reaches the SQLite file") { + let url = scratch.appendingPathComponent("secret-check.sqlite") + let secrets = InMemorySecretStore() + let parsed = try ConnectionString.parse("postgresql://ro:Tr0ub4dor-UNIQUE@db.example.com/app") + let bot = DatabaseBot(displayName: "x", connection: parsed.connection) + try secrets.set(parsed.password!, for: bot.keychainAccount) + do { let s = try Store(url: url); try s.saveBot(bot) } + for f in [url.path, url.path + "-wal"] where FileManager.default.fileExists(atPath: f) { + let bytes = try Data(contentsOf: URL(fileURLWithPath: f)) + expect(bytes.range(of: Data("Tr0ub4dor-UNIQUE".utf8)) == nil, "password found in \(f)") + } + let perms = (try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int) ?? 0 + expectEq(perms & 0o077, 0, "store is private to the user") +} + +// MARK: - Auth + +print("Authentication") +check("PKCE S256 = base64url(SHA-256(verifier)), no padding") { + // Reference computed independently: + // printf %s | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=' + expectEq(PKCE(verifier: "dBjftJeZ4CVP-mB92K9uhbUJU22SpH2AbDj4gfmTU2c").challenge, "T79ClVwiB0HLeuD28gSCyvDxozvQf-CecIwlBdoQMAE") + let g = PKCE.generate(); expect(g.verifier.count >= 43 && g.verifier.count <= 128) + expect(PKCE.generate().verifier != g.verifier) +} + +struct FakeTransport: AuthTransport { + let handler: @Sendable (URL, [String: String]) throws -> Data + func post(_ url: URL, form: [String: String]) async throws -> Data { try handler(url, form) } +} +final class FormLog: @unchecked Sendable { var forms: [[String: String]] = [] } + +await checkAsync("auth lifecycle: authorize → callback → token → restore → refresh → sign out") { + let secrets = InMemorySecretStore(), log = FormLog() + let cfg = AuthConfiguration(brokerURL: URL(string: "https://auth.pgbot.dev")!) + let svc = AuthService(config: cfg, secrets: secrets, transport: FakeTransport { _, form in + log.forms.append(form) + let exp = form["grant_type"] == "refresh_token" ? 3600 : -1 // first token is already expired → forces refresh on restore + return Data(#"{"access_token":"at-\#(log.forms.count)","refresh_token":"rt","expires_in":\#(exp),"user":{"id":"u1","name":"Ada","email":"ada@example.com"}}"#.utf8) + }) + let req = try svc.makeRequest(for: .github) + let q = URLComponents(url: req.url, resolvingAgainstBaseURL: false)!.queryItems! + expectEq(q.first { $0.name == "code_challenge_method" }?.value, "S256") + expectEq(q.first { $0.name == "code_challenge" }?.value, req.pkce.challenge) + expect(!req.url.absoluteString.contains(req.pkce.verifier), "verifier never leaves the app in the browser leg") + expect(!req.url.absoluteString.contains("secret"), "no client secret in the app") + + // Forged state is rejected. + do { _ = try await svc.complete(req, callback: URL(string: "pgbot://auth/callback?code=c&state=evil")!); expect(false) } + catch let e as AuthError { expectEq(e, .stateMismatch) } + + let session = try await svc.complete(req, callback: URL(string: "pgbot://auth/callback?code=c0de&state=\(req.state)")!) + expectEq(session.user.name, "Ada"); expectEq(log.forms.last?["code_verifier"], req.pkce.verifier) + let restored = try await svc.restore() + expectEq(restored?.accessToken, "at-2", "expired session refreshed on restore") + expectEq(log.forms.last?["grant_type"], "refresh_token") + try svc.signOut() + let afterSignOut = try await svc.restore() + expect(afterSignOut == nil) +} +await checkAsync("auth: a rejected refresh signs the user out") { + let secrets = InMemorySecretStore() + let svc = AuthService(config: .init(brokerURL: URL(string: "https://a.example")!), secrets: secrets, + transport: FakeTransport { _, form in + if form["grant_type"] == "refresh_token" { throw AuthError.expired } + return Data(#"{"access_token":"a","refresh_token":"r","expires_in":-1}"#.utf8) }) + let req = try svc.makeRequest(for: .google) + _ = try await svc.complete(req, callback: URL(string: "pgbot://auth/callback?code=x&state=\(req.state)")!) + do { _ = try await svc.restore(); expect(false, "should throw expired") } catch let e as AuthError { expectEq(e, .expired) } + expectEq(try secrets.get(SecretAccount.authSession), nil) +} +check("unconfigured builds refuse OAuth and never accept a plain-http broker") { + expect(!AuthConfiguration(brokerURL: nil).isConfigured) + let svc = AuthService(config: .init(brokerURL: nil), secrets: InMemorySecretStore()) + do { _ = try svc.makeRequest(for: .google); expect(false) } catch let e as AuthError { expectEq(e, .notConfigured) } +} + +// MARK: - Engine runner (fake engine) + +print("Engine adapter") +let fake = scratch.appendingPathComponent("fake-pgbot") +try """ +#!/bin/sh +# Echo what the engine would see, so checks can assert on it. +case "$1" in + sleep) sleep 30 ;; + slowok) sleep 1; echo ok ;; + fail) echo "pgbot: dial postgresql://u:$FAKE_SECRET@h/db failed: connection refused" >&2; exit 3 ;; + *) printf 'ARGV=%s\\n' "$*"; env | sort ;; +esac +""".write(to: fake, atomically: true, encoding: .utf8) +try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: fake.path) + +await checkAsync("credentials travel by environment only; parent secrets are not inherited") { + setenv("DATABASE_URL", "postgres://leak:leak@evil/db", 1) + setenv("OPENAI_API_KEY", "sk-parent-leak", 1) + defer { unsetenv("DATABASE_URL"); unsetenv("OPENAI_API_KEY") } + let runner = EngineRunner(binary: fake, stateDirectory: scratch.appendingPathComponent("state")) + let target = EngineTarget(connection: DatabaseConnection(host: "db", username: "ro"), password: "pw-SECRET-1") + let out = try await runner.run(.init(arguments: ["inspect", "--json"], + environment: target.environmentForChecks, secrets: target.secretsForChecks)) + let text = String(decoding: out.stdout, as: UTF8.self) + let argv = text.split(separator: "\n").first { $0.hasPrefix("ARGV=") } ?? "" + expect(!argv.contains("pw-SECRET-1") && !argv.contains("postgres"), "argv: \(argv)") + expect(text.contains("PGBOT_DATABASE_URL=postgresql://ro:pw-SECRET-1@db"), "DSN delivered via env") + expect(!text.contains("sk-parent-leak") && !text.contains("leak@evil"), "parent env leaked into the engine") + expect(text.contains("NO_COLOR=1") && text.contains("XDG_STATE_HOME="), "isolated, colorless engine env") +} +await checkAsync("stderr is redacted, including the exact password") { + let runner = EngineRunner(binary: fake, stateDirectory: scratch) + let out = try await runner.run(.init(arguments: ["fail"], environment: ["FAKE_SECRET": "zz-Unusual-77"], secrets: ["zz-Unusual-77"])) + expectEq(out.exitCode, 3) + expect(!out.stderr.contains("zz-Unusual-77"), out.stderr) + if case .connection(.unreachable, _) = EngineError.classify(stderr: out.stderr) {} else { expect(false, "classified as unreachable") } +} +await checkAsync("timeouts kill the engine and surface a timeout error") { + let runner = EngineRunner(binary: fake, stateDirectory: scratch) + let t0 = Date() + do { _ = try await runner.run(.init(arguments: ["sleep"], timeout: .milliseconds(400))); expect(false, "should time out") } + catch let e as EngineError { if case .timedOut = e {} else { expect(false, "\(e)") } } + expect(Date().timeIntervalSince(t0) < 5, "returned promptly") +} +await checkAsync("cancellation terminates the child") { + let runner = EngineRunner(binary: fake, stateDirectory: scratch) + let task = Task { try await runner.run(.init(arguments: ["sleep"], timeout: .seconds(60))) } + try await Task.sleep(for: .milliseconds(300)); task.cancel() + let t0 = Date() + do { _ = try await task.value; expect(false, "should be cancelled") } catch is CancellationError {} catch { expect(false, "\(error)") } + expect(Date().timeIntervalSince(t0) < 5) +} +await checkAsync("concurrency limit bounds simultaneous engine runs") { + let runner = EngineRunner(binary: fake, stateDirectory: scratch, maxConcurrent: 2) + let t0 = Date() + try await withThrowingTaskGroup(of: Void.self) { g in + for _ in 0..<4 { g.addTask { _ = try await runner.run(.init(arguments: ["slowok"])) } } + try await g.waitForAll() + } + let elapsed = Date().timeIntervalSince(t0) + expect(elapsed >= 1.9, "4 one-second runs at concurrency 2 take ≥2s, took \(elapsed)") +} +await checkAsync("missing engine is a clear, actionable error") { + let runner = EngineRunner(binary: scratch.appendingPathComponent("nope"), stateDirectory: scratch) + do { _ = try await runner.run(.init(arguments: [])); expect(false) } + catch let e as EngineError { if case .engineMissing = e {} else { expect(false, "\(e)") }; expect(!e.hint.isEmpty) } +} + +// MARK: - PSQL console + +print("PSQL mode") +check("meta-commands translate to catalog queries") { + if case .meta(let sql, let title) = PSQL.parse("\\dt") { expect(sql.contains("relkind IN ('r', 'p')")); expectEq(title, "List of tables") } else { expect(false) } + if case .meta(let sql, _) = PSQL.parse("\\di+") { expect(sql.contains("pg_total_relation_size") && sql.contains("\"Table\"")) } else { expect(false) } + if case .meta(let sql, let title) = PSQL.parse("\\d public.orders") { + expect(sql.contains("n.nspname ~ '^(public)$'") && sql.contains("c.relname ~ '^(orders)$'")); expectEq(title, "Table public.orders") + } else { expect(false) } + expectEq(PSQL.parse("\\x"), .toggleExpanded(nil)); expectEq(PSQL.parse("\\x on"), .toggleExpanded(true)) + expectEq(PSQL.parse("\\?"), .help); expectEq(PSQL.parse("\\q"), .quit) + expectEq(PSQL.parse("select 1;"), .sql("select 1;")) +} +check("psql patterns: wildcards, case folding, quoted names") { + if case .meta(let sql, _) = PSQL.parse("\\dt Order*") { expect(sql.contains("'^(order.*)$'"), sql) } else { expect(false) } + if case .meta(let sql, _) = PSQL.parse("\\dt \"Order\"") { expect(sql.contains("'^(Order)$'"), sql) } else { expect(false) } +} +check("hostile patterns can't break out of the SQL literal") { + if case .meta(let sql, _) = PSQL.parse("\\dt x'; drop table t; --") { + expect(sql.contains("'^(x''; drop table t; --)$'"), sql) + expect(!sql.contains("x'; drop"), "quote must be doubled") + } else { expect(false) } +} +check("shell, file and session meta-commands are refused") { + for c in ["\\! rm -rf /", "\\o /tmp/out", "\\copy t to '/tmp/x'", "\\i evil.sql", "\\set AUTOCOMMIT off", "\\c otherdb"] { + if case .unsupported = PSQL.parse(c) {} else { expect(false, "\(c) should be refused") } + } +} +check("Return runs only complete statements (psql semantics)") { + expect(PSQL.isComplete("select 1;")) + expect(PSQL.isComplete("\\dt")) + expect(!PSQL.isComplete("select 1")) + expect(!PSQL.isComplete("select ';")) + expect(PSQL.isComplete("select ';' ;")) + expect(!PSQL.isComplete("do $$ begin perform 1; end")) + expect(PSQL.isComplete("do $$ begin perform 1; end $$;")) + expect(PSQL.isComplete("select 1; -- note"), "a comment after the semicolon doesn't hide it") + expect(PSQL.isComplete("select 1 -- note\n;")) +} +check("psql results round-trip through the conversation store format") { + let m = ChatMessage(botID: UUID(), role: .assistant, payload: .psqlResult(PSQLResultPayload( + input: "select 1;", title: nil, output: SQLRunOutput(results: [], error: nil, elapsedMS: 1), expanded: false))) + let data = try EngineJSON.encoder().encode(m) + expectEq(try EngineJSON.decoder().decode(ChatMessage.self, from: data).payload, m.payload) +} + +check("decodes the engine's sql run --json document (contract pinned by TestSQLRunJSONContract)") { + // Shape emitted by cmd/pgbot/sqlrun.go; a future additive key must not break decoding. + let json = #""" + {"sql_run_schema_version":"1.0.0","read_only":true,"future_key":1, + "results":[{"statement":"select id, note from t","command":"SELECT 2", + "columns":[{"name":"id","type":"integer"},{"name":"note","type":"text"}], + "rows":[["1",null],["2","b"]],"row_count":2,"truncated":true,"elapsed_ms":1.5}], + "error":{"statement_index":1,"statement":"selec 2","message":"syntax error at or near \"selec\"","sqlstate":"42601","position":1}, + "elapsed_ms":3.25} + """# + let out = try EngineJSON.decoder().decode(SQLRunOutput.self, from: Data(json.utf8)) + expect(out.readOnly) + expectEq(out.results.first?.rows, [["1", nil], ["2", "b"]]) + expectEq(out.results.first?.truncated, true) + expectEq(out.error?.position, 1); expectEq(out.error?.statementIndex, 1) + expect(out.error?.isRefusal == false) + let ok = try EngineJSON.decoder().decode(SQLRunOutput.self, from: Data(#"{"read_only":true,"results":[],"elapsed_ms":0}"#.utf8)) + expect(ok.error == nil, "success omits error") +} +check("numeric columns right-align; text doesn't") { + for t in ["integer", "bigint", "numeric(10,2)", "double precision", "NUMERIC"] { expect(SQLRunColumn(name: "x", type: t).isNumeric, t) } + for t in ["text", "character varying", "timestamp with time zone", "integer[]", "uuid"] { expect(!SQLRunColumn(name: "x", type: t).isNumeric, t) } +} +check("psql result plain text is tab-separated with NULL as empty") { + let p = PSQLResultPayload(input: "select a, b from t;", title: nil, output: SQLRunOutput(results: [ + SQLRunResult(statement: "", command: "SELECT 1", columns: [.init(name: "a", type: "int"), .init(name: "b", type: "text")], + rows: [["1", nil]], rowCount: 1, truncated: false, elapsedMS: 0), + SQLRunResult(statement: "", command: "SET", columns: [], rows: [], rowCount: 0, truncated: false, elapsedMS: 0), + ], error: SQLRunError(message: "boom"), elapsedMS: 0), expanded: false) + expectEq(p.plainText, "select a, b from t;\na\tb\n1\t\nSET\nERROR: boom") +} +check("a meta-command lookup never reaches the engine as a backslash") { + for c in ["\\dt", "\\d+ orders", "\\l", "\\dn", "\\di", "\\df", "\\du", "\\dx", "\\conninfo", "\\dv", "\\dm", "\\ds"] { + guard case .meta(let sql, _) = PSQL.parse(c) else { expect(false, "\(c) should be a meta-command"); continue } + expect(!sql.contains("\\"), "\(c) → SQL without a backslash") + expect(sql.lowercased().hasPrefix("select") || sql.lowercased().hasPrefix("with"), "\(c) is a read-only query") + } +} + +// MARK: - Live engine integration + +let env = ProcessInfo.processInfo.environment +if let dsn = env["PGBOT_TEST_DSN"], let enginePath = env["PGBOT_ENGINE_PATH"] { + print("Live engine (\(enginePath))") + // Resolve a relative PGBOT_ENGINE_PATH against the working directory up front. + let engineURL = URL(fileURLWithPath: enginePath, relativeTo: URL(fileURLWithPath: FileManager.default.currentDirectoryPath)).standardizedFileURL + let runner = EngineRunner(binary: engineURL, stateDirectory: scratch.appendingPathComponent("live-state")) + let engine = PGBotEngine(runner: runner) + let parsed = try ConnectionString.parse(dsn) + let target = EngineTarget(connection: parsed.connection, password: parsed.password) + + await checkAsync("engine version is readable") { + let v = try await engine.version(); expect(!v.isEmpty, v); print(" engine \(v)") + } + await checkAsync("real inspection decodes and scores like the CLI") { + let ctx = try await engine.inspect(target) + expectEq(ctx.schemaMajor, 1) + expect(ctx.server.versionNum >= 100000, "server version") + let score = HealthScore.from(ctx) + print(" \(ctx.server.displayVersion) · \(ctx.findings.count) findings · score \(score.value) (\(score.completeness.rawValue))") + // Cross-check against the engine's own rendering of the same number. + let text = try await runner.run(.init(arguments: ["inspect", "--no-store"], environment: target.environmentForChecks, secrets: target.secretsForChecks)) + let rendered = String(decoding: text.stdout, as: UTF8.self) + if let m = rendered.firstMatch(of: #/Database health:\s*(\d+)\/100/#) { + let cliScore = Int(m.1)! + // The two runs are seconds apart; the finding set can legitimately differ by a sampled finding. + expect(abs(cliScore - score.value) <= 3, "CLI said \(cliScore), app computed \(score.value)") + } + let rec = InspectionRecord(botID: UUID(), startedAt: Date(), finishedAt: Date(), context: ctx) + expect(!MetricKey.samples(from: rec).isEmpty, "metrics extracted from a real run") + } + await checkAsync("multiple simultaneous databases inspect independently") { + async let a = engine.inspect(target) + async let b = engine.inspect(target) + let (x, y) = try await (a, b) + expectEq(x.fingerprint, y.fingerprint) + } + await checkAsync("activity and setup SQL come back structured") { + let sessions = try await engine.activity(target) + expect(sessions.allSatisfy { $0.pid > 0 }) + let sql = try await engine.setupSQL(role: "pgbot_ro", database: parsed.connection.database, includeLogs: false) + expect(sql.contains("pg_monitor"), "init recipe grants pg_monitor") + } + await checkAsync("bad credentials classify as an authentication problem without leaking the password") { + var bad = parsed.connection; bad.username = "pgbot_no_such_user" + do { _ = try await engine.inspect(EngineTarget(connection: bad, password: "WrongPass-123")); expect(false) } + catch let e as EngineError { + if case .connection(let p, let d) = e { expect(p == .authentication || p == .other, "\(p)"); expect(!d.contains("WrongPass-123")) } + else { expect(false, "\(e)") } + } + } + await checkAsync("PSQL mode: queries return typed rows, writes are blocked, COMMIT is refused") { + let ok = try await engine.runSQL(target, sql: "select 1 as one, null::text as nothing; select 'b' as two;", maxRows: 10) + expect(ok.error == nil, "\(String(describing: ok.error))") + expectEq(ok.results.count, 2) + expectEq(ok.results.first?.columns.map(\.type), ["integer", "text"]) + let row = ok.results.first?.rows.first ?? [] + expect(row.count == 2 && row[0] == "1" && row[1] == nil, "NULL arrives as nil, not \"\": \(row)") + let write = try await engine.runSQL(target, sql: "create table pgbot_should_not_exist(a int);", maxRows: 10) + expectEq(write.error?.sqlstate, "25006") + let refused = try await engine.runSQL(target, sql: "select 1; commit;", maxRows: 10) + expect(refused.error?.isRefusal == true && refused.results.isEmpty, "refused before anything ran") + } + await checkAsync("PSQL mode: \\dt and \\d run against the real catalog") { + guard case .meta(let dt, _) = PSQL.parse("\\dt") else { expect(false); return } + let tables = try await engine.runSQL(target, sql: dt, maxRows: 100) + expect(tables.error == nil, "\(String(describing: tables.error))") + guard case .meta(let d, _) = PSQL.parse("\\d pg_catalog.pg_class") else { expect(false); return } + let described = try await engine.runSQL(target, sql: d, maxRows: 200) + expect(described.error == nil && described.results.count == 2, "\(String(describing: described.error))") + expect(described.results.first?.rows.contains { $0.first == "relname" } == true, "pg_class has a relname column") + } + await checkAsync("unreachable host classifies as unreachable") { + var bad = parsed.connection; bad.host = "127.0.0.1"; bad.port = 1; bad.connectTimeoutSeconds = 2 + do { _ = try await engine.inspect(EngineTarget(connection: bad, password: nil)); expect(false) } + catch let e as EngineError { if case .connection(.unreachable, _) = e {} else { expect(false, "\(e)") } } + } +} else { + print("Live engine: skipped (set PGBOT_TEST_DSN and PGBOT_ENGINE_PATH)") +} + +// MARK: - Summary + +print("") +if failures.isEmpty { + print("All \(passed) checks passed.") + exit(0) +} else { + print("\(failures.count) failure(s), \(passed) passed:") + failures.forEach { print(" • \($0)") } + exit(1) +} From e196f2ffc13428e12585ff1f3ccb9c3e306bf2ff Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:03:36 -0800 Subject: [PATCH 3/8] =?UTF-8?q?feat(desktop):=20PGBot=20for=20macOS=20?= =?UTF-8?q?=E2=80=94=20chat-first=20SwiftUI=20app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One bot per PostgreSQL database, built on PGBotKit and the bundled engine: - Chat per database with health reports, findings, plans and tables; answers from `pgbot ask` behind an explicit per-provider consent sheet. - PSQL mode (+ → PSQL Mode, ⌘⇧P): a read-only psql console in the chat with history, psql Return semantics, typed result tables, \x records, copy as TSV/CSV/Markdown and psql-style errors with a caret. - Metrics charts, logs with filters, notification center, menu bar extra, and macOS notifications with per-category, severity, quiet-hours and per-database settings. - Settings: appearance (theme, accent, text size, density, message style, avatars), new-database defaults, monitoring, AI providers, privacy. - Demo mode (clearly labelled), onboarding and add-database flows with the read-only role setup SQL. scripts/build-app.sh builds the universal engine and assembles a signed PGBot.app; launch scenarios support screenshots and UI automation. Co-Authored-By: Claude Opus 5.5 --- desktop/macos/Package.swift | 2 + desktop/macos/README.md | 183 ++++ .../macos/Sources/PGBot/App/AppModel.swift | 922 ++++++++++++++++++ .../macos/Sources/PGBot/App/AppSettings.swift | 181 ++++ .../macos/Sources/PGBot/App/PGBotApp.swift | 120 +++ .../PGBot/Components/ElephantAvatar.swift | 129 +++ .../PGBot/Components/HealthScoreView.swift | 78 ++ .../PGBot/Components/MessageView.swift | 521 ++++++++++ .../Sources/PGBot/Components/PSQLViews.swift | 258 +++++ .../PGBot/DesignSystem/DesignSystem.swift | 373 +++++++ .../Features/Authentication/SignInView.swift | 123 +++ .../PGBot/Features/Chat/BotDetailView.swift | 141 +++ .../Features/Chat/ConversationView.swift | 273 ++++++ .../PGBot/Features/Logs/LogsView.swift | 160 +++ .../PGBot/Features/Metrics/MetricsView.swift | 563 +++++++++++ .../NotificationCenterView.swift | 237 +++++ .../Onboarding/AddDatabaseSheet.swift | 264 +++++ .../Features/Onboarding/OnboardingView.swift | 32 + .../Features/Settings/AppSettingsView.swift | 530 ++++++++++ .../Settings/DatabaseSettingsView.swift | 180 ++++ .../PGBot/Features/Sidebar/MainView.swift | 423 ++++++++ desktop/macos/scripts/build-app.sh | 87 ++ 22 files changed, 5780 insertions(+) create mode 100644 desktop/macos/README.md create mode 100644 desktop/macos/Sources/PGBot/App/AppModel.swift create mode 100644 desktop/macos/Sources/PGBot/App/AppSettings.swift create mode 100644 desktop/macos/Sources/PGBot/App/PGBotApp.swift create mode 100644 desktop/macos/Sources/PGBot/Components/ElephantAvatar.swift create mode 100644 desktop/macos/Sources/PGBot/Components/HealthScoreView.swift create mode 100644 desktop/macos/Sources/PGBot/Components/MessageView.swift create mode 100644 desktop/macos/Sources/PGBot/Components/PSQLViews.swift create mode 100644 desktop/macos/Sources/PGBot/DesignSystem/DesignSystem.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Authentication/SignInView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Chat/BotDetailView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Logs/LogsView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Metrics/MetricsView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Notifications/NotificationCenterView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Onboarding/AddDatabaseSheet.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Onboarding/OnboardingView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Settings/AppSettingsView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Settings/DatabaseSettingsView.swift create mode 100644 desktop/macos/Sources/PGBot/Features/Sidebar/MainView.swift create mode 100755 desktop/macos/scripts/build-app.sh diff --git a/desktop/macos/Package.swift b/desktop/macos/Package.swift index f6a18df..451a074 100644 --- a/desktop/macos/Package.swift +++ b/desktop/macos/Package.swift @@ -15,10 +15,12 @@ let package = Package( name: "PGBotDesktop", platforms: [.macOS(.v14)], products: [ + .executable(name: "PGBot", targets: ["PGBot"]), .library(name: "PGBotKit", targets: ["PGBotKit"]), ], targets: [ .target(name: "PGBotKit", path: "Sources/PGBotKit", linkerSettings: [.linkedLibrary("sqlite3")]), + .executableTarget(name: "PGBot", dependencies: ["PGBotKit"], path: "Sources/PGBot"), .executableTarget(name: "PGBotKitChecks", dependencies: ["PGBotKit"], path: "Tests/PGBotKitChecks"), ] ) diff --git a/desktop/macos/README.md b/desktop/macos/README.md new file mode 100644 index 0000000..470f3c4 --- /dev/null +++ b/desktop/macos/README.md @@ -0,0 +1,183 @@ +# PGBot for macOS + +A native SwiftUI app on top of the pgbot engine: one chat-first bot per +PostgreSQL database, with proactive reports, metrics and logs. + +The app contains **no diagnostics**. Every score, finding, metric and log +line comes from the bundled `pgbot` binary's machine contracts +(`inspect --json`, `logs --json`, `activity --json`, `ask`, `sql explain`, +`sql run`, `why`, `diff`, `init`). The Swift side does presentation, scheduling, +persistence, and security plumbing only. + +## Build and run + +Requirements: macOS 14+, Swift 5.10 (Command Line Tools are enough), Go (to build the engine). + +```sh +desktop/macos/scripts/build-app.sh # → desktop/macos/build/PGBot.app (signed ad hoc) +open desktop/macos/build/PGBot.app +``` + +* The engine is built from this repo for arm64 and amd64 and merged with `lipo`. + The Swift binary is universal when full Xcode is present. With Command Line + Tools it is host-architecture only. +* `PGBOT_AUTH_BROKER_URL=https://… build-app.sh` enables Google/GitHub sign-in + (see Authentication). Without it, the app offers "Continue without an account". +* `CODESIGN_IDENTITY="Developer ID Application: …"` signs for distribution + (notarization is not scripted yet). + +### Tests + +```sh +cd desktop/macos +swift run PGBotKitChecks # 49 unit checks +PGBOT_TEST_DSN='postgresql://pgbot_ro:…@127.0.0.1:5432/postgres?sslmode=disable' \ +PGBOT_ENGINE_PATH=../../bin/pgbot swift run PGBotKitChecks # + 8 live-engine checks +``` + +Command Line Tools ship without XCTest, so the suite is an executable runner +that exits non-zero on failure. It covers: + +* the health-score formula +* JSON contract decoding +* connection-string parsing +* redaction +* the Keychain +* finding diff and notification dedup +* scheduler backoff and sleep/wake +* SQLite persistence, including a check that no password reaches the store file +* PKCE and the auth lifecycle +* engine-runner security: argv, environment isolation, stderr scrubbing, timeout, cancellation, concurrency limit +* PSQL mode: meta-command translation, pattern quoting, refused commands, the + `sql run --json` contract +* a live run against a real database, including PSQL mode's read-only guarantees + +The engine side of PSQL mode is covered by `go test ./cmd/pgbot/ -run 'SQL|Refuse'` +(plus `TestIntegration_sqlRun` with `PGBOT_TEST_SUPERUSER_DSN`). +`.github/workflows/desktop-macos.yml` runs all of it on macOS CI and builds the +bundle. UI tests are not written yet; they need Xcode. + +### Launch scenarios (screenshots, UI automation) + +```sh +open PGBot.app --args -PGBotScenario demo [-PGBotRoute metrics|logs] [-PGBotSelect 2] [-PGBotAppearance dark] +PGBOT_DATA_DIR=/tmp/pgbot-ui PGBOT_SCENARIO_DSN='postgresql://…' PGBot.app/Contents/MacOS/PGBot -PGBotScenario local +``` + +Add `-PGBotSettings '{accent = pink; textSize = large; bubbleStyle = plain; density = compact;}'` to +overlay any setting, and `-PGBotOpenSettings YES -settingsTab appearance` to open Settings on a tab. +Scenarios use an in-memory session and never persist settings or the demo flag. +`PGBOT_DATA_DIR` isolates the store and uses a separate Keychain service. + +## Architecture + +``` +SwiftUI views (Sources/PGBot) + └─ AppModel state, routing, conversations, notifications + ├─ InspectionScheduler per-bot intervals, backoff, sleep/wake, global pause + ├─ PGBotEngine typed calls → EngineRunner → bundled pgbot binary + ├─ Store SQLite (bots, messages, inspections, metric samples, notifications) + ├─ KeychainStore DB passwords, AI keys, auth session + └─ AuthService OAuth 2.0 + PKCE via a broker +PGBotKit (Sources/PGBotKit) all of the above except the views; no SwiftUI, fully checkable +``` + +| Need | Reused from the engine | New in the app | +|---|---|---| +| Health, findings, metrics | `inspect --json` (Context schema 1.x) | Swift `Codable` mirror; additive keys ignored | +| Health score | `render.HealthScore` formula | Ported 1:1 (see below), plus a completeness gate | +| What changed | Baseline store, `monitor.Compare` semantics | Same id+object diff in Swift; announcement ledger | +| AI answers | `pgbot ask` (grounded on findings, safety footer) | Provider picker, Keychain keys, consent sheet | +| Explain SQL | `sql explain` (plan-only, read-only txn) | SQL over stdin, rendered plan | +| PSQL mode | `sql run --json` (one READ ONLY txn, always rolled back) | psql meta-commands as catalog queries, result tables | +| Logs | `logs --json` (literals scrubbed) | Filters, search, "Explain with PGBot" (re-redacted) | +| Sessions | `activity --json` | Table message | +| Read-only role | `init --role … --database …` | Setup-SQL sheet in Add Database | + +### Security invariants + +These are enforced in `EngineRunner` and asserted by the checks. + +* **No credentials in argv.** The DSN goes in `PGBOT_DATABASE_URL`, AI keys in + `PGBOT_AI_API_KEY`, and SQL over stdin. `ps` shows flags only. +* **Allow-listed child environment.** The engine does not inherit the app's + environment, so a stray `DATABASE_URL`/`OPENAI_API_KEY` can't redirect a run + or leak a key. `XDG_STATE_HOME` points at the app's own baseline store, + separate from the CLI's. +* **Redacted stderr.** Engine stderr is redacted (DSN passwords, `key=value` + secrets, provider keys, bearer tokens, e-mails, plus the exact password) + before it reaches the UI or a message. +* **Bounded runs.** Every run has a timeout and SIGTERM→SIGKILL cancellation, + under a global concurrency limit of 3. +* **Secrets only in the Keychain.** Passwords and keys are stored as + `…AfterFirstUnlockThisDeviceOnly` items: never synced, and readable for + background monitoring once the user has logged in. The SQLite file is 0600 + and has no password field. +* **Read-only.** Nothing is executed beyond the engine's read-only + inspections and PSQL mode's `sql run`, which runs in a READ ONLY transaction + that is always rolled back and refuses transaction control, COPY, dblink and + server actions before sending anything. Destructive remediation (DROP/ALTER/…) is shown as text for the + user to review, and the engine's `safety.blocking_caveats` render as red + guards on the finding. +* **Explicit AI consent.** Asking an external AI provider requires consent + per provider and endpoint. Local endpoints (Ollama) skip it because nothing + leaves the Mac. + +### Health score + +The engine computes `100 − 10·critical − 3·warn − 1·info` (suppressed findings +skipped, floor 0) in `internal/render/dashboard.go`, but does not emit it in +`--json`. The app mirrors that formula in `HealthScore.engineScore`, pinned by +checks. The live check compares it with the CLI's own +`Database health: N/100`. + +The app also refuses a confident grade when Health and Activity are both +unavailable (shown as "—"), and marks the grade "Incomplete" when any core +section is unavailable or `pg_monitor` is missing. + +**Suggested engine follow-up:** emit `health_score` in the Context JSON +(additive, schema 1.7.0) so there is a single source of truth. + +### Monitoring and notifications + +* Each bot has its own interval and daily-report hour. Failures back off from + 1 min, doubling, capped at the bot's own interval. +* On sleep the scheduler suspends. On wake, each overdue bot runs once. +* The UI states plainly that monitoring only covers time while the Mac is + awake and PGBot is open (or in the menu bar). +* Notifications come from the id+object diff and are deduplicated by a + per-bot ledger. An unchanged finding is never re-announced, even across + failed runs or restarts. An outage is announced once, and so is the + recovery. Mute, quiet hours, severity threshold, and per-category toggles + are respected for system banners. The in-app center always records. + +### Authentication + +`AuthService` implements the authorization-code flow with PKCE (S256), state +validation (constant-time), token refresh, and sign-out. The browser leg uses +`ASWebAuthenticationSession`. Because the app must not hold Google/GitHub +client secrets, token exchange goes through a **PGBot auth broker**, which +does not exist yet. It must expose: + +* `GET {broker}/oauth/{google|github}/authorize?response_type=code&client_id=pgbot-desktop&redirect_uri=pgbot://auth/callback&code_challenge=…&code_challenge_method=S256&state=…` +* `POST {broker}/oauth/token` (form), with `grant_type=authorization_code|refresh_token`. Returns + `{access_token, refresh_token, expires_in, user:{id,name,email,avatar_url}, plan}` + +Until the broker is configured, sign-in buttons are disabled and the user can +continue with a local-only profile. + +## Not done yet + +* **Auth broker service.** Required for real Google/GitHub sign-in (see above). +* **Universal Swift binary and notarization.** Both need full Xcode. +* **XCUITest suite.** Launch scenarios are in place for it. +* **Streaming AI responses.** `pgbot ask` returns the whole answer; the UI + shows elapsed time and Stop. +* **Provider infrastructure metrics** (CloudWatch, Cloud SQL, Azure Monitor) + and **provider log APIs** (Supabase, Neon). The UI says these are + unavailable rather than estimating them. +* **Pro / cloud features.** Cloud monitoring, Slack/email/webhooks, teams, + billing and sync are modelled (`Subscription`, `ProFeature`) but not built. +* **Ignore rules.** App-level "Ignore" is local to the app and does not write + the engine's `[[ignore]]` rules. +* **Per-bot AI provider overrides.** There is one global provider. diff --git a/desktop/macos/Sources/PGBot/App/AppModel.swift b/desktop/macos/Sources/PGBot/App/AppModel.swift new file mode 100644 index 0000000..085bcbf --- /dev/null +++ b/desktop/macos/Sources/PGBot/App/AppModel.swift @@ -0,0 +1,922 @@ +import AppKit +import Network +import Observation +import PGBotKit +import ServiceManagement +import SwiftUI +import UserNotifications + +/// The app's single source of truth. Views read it; every side effect (engine, +/// Keychain, store, notifications) goes through it. +@MainActor @Observable +final class AppModel { + // MARK: State + + var auth: AuthPhase = .restoring + var bots: [DatabaseBot] = [] + var selection: UUID? { + didSet { + guard let s = selection else { return } + markBotRead(s) + if !demoMode && scenario == nil { try? realStore.setValue(s, for: "lastSelection") } + } + } + var route: DetailRoute = .chat + var conversations: [UUID: [ChatMessage]] = [:] + var latest: [UUID: InspectionRecord] = [:] + var previous: [UUID: InspectionRecord] = [:] + var inspecting: Set = [] + var generating: [UUID: Task] = [:] + var notifications: [AppNotification] = [] + var settings = AppSettings() { didSet { if settings != oldValue { persistSettings(oldValue) } } } + var engineVersion: String? + var engineProblem: EngineError? + var demoMode = false + var isOffline = false + var scrollTarget: UUID? + + // Sheets / panels + var showingAddDatabase = false + var showingSearch = false + var showingNotifications = false + var settingsForBot: DatabaseBot? + var pendingConsent: PendingConsent? + var explainSQLDraft: String? + + // PSQL mode (per database): the composer becomes a read-only psql console. + var psqlBots: Set = [] + var psqlExpanded = false + var psqlHistory: [UUID: [String]] = [:] + + struct PendingConsent: Identifiable { let id = UUID(); let botID: UUID; let question: String; let ai: AIConfiguration } + + // MARK: Services + + private(set) var store: Store + private let realStore: Store + let secrets: SecretStore + let authService: AuthService + private(set) var engine: DiagnosticEngine? + private var scheduler: InspectionScheduler! + private var dailyTimer: Timer? + private var demoBundle: DemoData.Bundle? + private var observers: [NSObjectProtocol] = [] + + /// Launch scenarios for screenshots and UI tests (`-PGBotScenario demo|local`). + /// They never persist a session or demo flag. + let scenario = UserDefaults.standard.string(forKey: "PGBotScenario") + static let env = ProcessInfo.processInfo.environment + + init() { + // PGBOT_DATA_DIR isolates the store and Keychain service (development, UI tests). + let isolated = Self.env["PGBOT_DATA_DIR"].map { URL(fileURLWithPath: $0, isDirectory: true) } + let support = isolated ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("PGBot", isDirectory: true) + let store: Store + do { store = try Store(url: support.appendingPathComponent("pgbot.sqlite")) } + catch { store = try! Store(url: nil) } // degraded: in-memory, surfaced via engineProblem-like banner below + self.realStore = store + self.store = store + self.secrets = KeychainStore(service: isolated == nil ? "dev.pgbot.desktop" : "dev.pgbot.desktop.isolated") + self.authService = AuthService(config: .fromBundle(), secrets: secrets) + self.settings = AppSettings.load(store.rawValue(for: "settings")) + Theme.apply(settings) + self.demoMode = store.value(Bool.self, for: "demoMode") ?? false + configureEngine(stateDirectory: support.appendingPathComponent("engine-state", isDirectory: true)) + scheduler = InspectionScheduler { [weak self] id in + guard let self else { return .failure } + return await self.scheduledInspection(id) + } + observeSystem() + } + + // MARK: Startup + + func start() async { + if let scenario { + auth = .signedIn(AuthenticationSession(user: User(id: "scenario", name: "Alex Example", email: nil, avatarURL: nil, provider: .local), + accessToken: "", refreshToken: nil, expiresAt: .distantFuture, subscription: .init())) + demoMode = scenario == "demo" + await loadWorkspace() + if let route = UserDefaults.standard.string(forKey: "PGBotRoute") { + self.route = route == "metrics" ? .metrics : (route == "logs" ? .logs : .chat) + } + if let raw = UserDefaults.standard.string(forKey: "PGBotSelect"), let i = Int(raw), bots.indices.contains(i) { selection = bots[i].id } + if let a = UserDefaults.standard.string(forKey: "PGBotAppearance"), let ap = AppSettings.Appearance(rawValue: a) { settings.appearance = ap } + // `-PGBotSettings '{…}'` arrives as a string or, parsed by NSArgumentDomain, as a dictionary. + switch UserDefaults.standard.object(forKey: "PGBotSettings") { + case let json as String: settings = settings.overlaid(with: Data(json.utf8)) + case let dict as [String: Any]: + if let data = try? JSONSerialization.data(withJSONObject: dict) { settings = settings.overlaid(with: data) } + default: break + } + // `-PGBotPSQL 'cmd ||| cmd'`: open PSQL mode on the selected database and run each command. + if let script = UserDefaults.standard.string(forKey: "PGBotPSQL") { + Task { + try? await Task.sleep(for: .seconds(1.5)) + guard let id = self.selection else { return } + self.setPSQLMode(true, for: id) + for cmd in script.components(separatedBy: "|||").map({ $0.trimmingCharacters(in: .whitespaces) }) where !cmd.isEmpty { + while self.generating[id] != nil || self.inspecting.contains(id) { try? await Task.sleep(for: .milliseconds(200)) } + self.runPSQL(cmd, on: id) + try? await Task.sleep(for: .milliseconds(300)) + } + } + } + if UserDefaults.standard.bool(forKey: "PGBotOpenSettings") { + // After any theme-driven rebuild of the root view has settled. + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { + openAppSettings() + } + } + if scenario == "local", let dsn = Self.env["PGBOT_SCENARIO_DSN"], let p = try? ConnectionString.parse(dsn), + !bots.contains(where: { $0.connection.instanceKey == p.connection.instanceKey && $0.connection.database == p.connection.database }) { + addBot(DatabaseBot(displayName: "Local Postgres", description: "Development database", + avatar: BotAvatar(color: .purple), environment: .local, connection: p.connection, pinned: true), + password: p.password, firstInspection: nil) + } + return + } + do { + if let s = try await authService.restore() { auth = .signedIn(s) } else { auth = .signedOut(error: nil) } + } catch { + auth = .signedOut(error: (error as? LocalizedError)?.errorDescription ?? error.localizedDescription) + } + if case .signedIn = auth { await loadWorkspace() } + } + + func loadWorkspace() async { + if demoMode { enterDemo() } else { loadReal() } + if let engine, engineVersion == nil { + do { engineVersion = try await engine.version() } catch { engineProblem = error as? EngineError ?? .failed(error.localizedDescription) } + } + await scheduler.start() + startDailyTimer() + if settings.notificationsEnabled { requestNotificationPermission() } + updateDockBadge() + } + + private func loadReal() { + store = realStore + bots = (try? store.bots()) ?? [] + for b in bots { + conversations[b.id] = (try? store.messages(for: b.id)) ?? [] + psqlHistory[b.id] = store.value([String].self, for: "psqlHistory.\(b.id)") ?? [] + let recent = (try? store.inspections(for: b.id, limit: 2)) ?? [] + latest[b.id] = recent.first + previous[b.id] = recent.dropFirst().first + } + notifications = (try? store.notifications()) ?? [] + if selection == nil || !bots.contains(where: { $0.id == selection }) { + let last = settings.restoreLastSelection ? store.value(UUID.self, for: "lastSelection") : nil + selection = bots.first { $0.id == last }?.id ?? bots.first?.id + } + Task { for b in bots { await registerSchedule(b) } } + } + + private func configureEngine(stateDirectory: URL) { + if let bin = EngineLocator.locate(override: settings.enginePathOverride) { + engine = PGBotEngine(runner: EngineRunner(binary: bin, stateDirectory: stateDirectory, maxConcurrent: 3)) + engineProblem = nil + } else { + engine = nil + engineProblem = .engineMissing("The pgbot engine wasn't found in the app bundle or on this Mac.") + } + } + + // MARK: Authentication + + var session: AuthenticationSession? { if case .signedIn(let s) = auth { return s }; return nil } + + func signIn(with provider: AuthProvider, using authenticator: WebAuthenticator) async { + auth = .signingIn(provider) + do { + let req = try authService.makeRequest(for: provider) + let callback = try await authenticator.authenticate(url: req.url, callbackScheme: authService.config.callbackScheme) + let session = try await authService.complete(req, callback: callback) + auth = .signedIn(session) + await loadWorkspace() + } catch AuthError.cancelled { + auth = .signedOut(error: nil) + } catch { + auth = .signedOut(error: (error as? LocalizedError)?.errorDescription ?? error.localizedDescription) + } + } + + func continueLocally() async { + let name = NSFullUserName().isEmpty ? "Local user" : NSFullUserName() + if let s = try? authService.continueLocally(name: name) { auth = .signedIn(s); await loadWorkspace() } + } + + func signOut() async { + try? authService.signOut() + await scheduler.stop() + for t in generating.values { t.cancel() } + generating = [:] + bots = []; conversations = [:]; latest = [:]; previous = [:]; notifications = []; selection = nil + auth = .signedOut(error: nil) + } + + // MARK: Demo mode + + func setDemoMode(_ on: Bool) { + demoMode = on + try? realStore.setValue(on, for: "demoMode") + conversations = [:]; latest = [:]; previous = [:]; selection = nil + if on { enterDemo() } else { loadReal() } + } + + private func enterDemo() { + // Demo data lives in its own in-memory store: it can never mix with real history. + let demoStore = try! Store(url: nil) + let d = DemoData.make() + for b in d.bots { try? demoStore.saveBot(b) } + for r in d.records { try? demoStore.save(r) } + for m in d.messages { try? demoStore.append(m) } + for n in d.notifications { try? demoStore.save(n) } + try? demoStore.insertSamples(d.samples) + store = demoStore + demoBundle = d + bots = d.bots + for b in bots { + conversations[b.id] = (try? demoStore.messages(for: b.id)) ?? [] + latest[b.id] = try? demoStore.latestInspection(for: b.id) + } + notifications = d.notifications + selection = bots.first?.id + } + + func demoLogs(for id: UUID) -> [LogEntry]? { demoBundle?.logs[id] } + + // MARK: Bots + + var selectedBot: DatabaseBot? { bots.first { $0.id == selection } } + func bot(_ id: UUID) -> DatabaseBot? { bots.first { $0.id == id } } + + func update(_ bot: DatabaseBot) { + guard let i = bots.firstIndex(where: { $0.id == bot.id }) else { return } + bots[i] = bot + try? store.saveBot(bot) + Task { await registerSchedule(bot) } + } + + func mutate(_ id: UUID, _ change: (inout DatabaseBot) -> Void) { + guard var b = bot(id) else { return } + change(&b) + update(b) + } + + /// Adds a bot, stores its password in the Keychain, and opens its conversation. + /// When the connection test already produced an inspection, it is reused as + /// the first report instead of inspecting twice. + func addBot(_ draft: DatabaseBot, password: String?, firstInspection: EngineContext?) { + var bot = draft + bot.sortOrder = (bots.map(\.sortOrder).max() ?? -1) + 1 + bot.isDemo = false + if let p = password, !p.isEmpty { try? secrets.set(p, for: bot.keychainAccount) } + bots.append(bot) + try? store.saveBot(bot) + selection = bot.id + route = .chat + post(ChatMessage(botID: bot.id, role: .system, payload: .connectionEvent("Connected to \(bot.connection.host) as \(bot.connection.username)", ok: true))) + Task { + await registerSchedule(bot) + if let ctx = firstInspection { + let now = Date() + record(bot.id, InspectionRecord(botID: bot.id, startedAt: now, finishedAt: now, context: ctx), reason: .first) + } else { + await inspect(bot.id, reason: .first) + } + } + } + + func remove(_ id: UUID) { + guard let b = bot(id) else { return } + try? secrets.delete(b.keychainAccount) + try? store.deleteBot(id) + bots.removeAll { $0.id == id } + conversations[id] = nil; latest[id] = nil; previous[id] = nil + notifications.removeAll { $0.botID == id } + generating[id]?.cancel(); generating[id] = nil + Task { await scheduler.unregister(id) } + if selection == id { selection = bots.first?.id } + } + + func move(from source: IndexSet, to destination: Int, within ids: [UUID]) { + var ordered = ids + ordered.move(fromOffsets: source, toOffset: destination) + for (i, id) in ordered.enumerated() { mutate(id) { $0.sortOrder = i } } + bots.sort { $0.sortOrder < $1.sortOrder } + } + + func password(for bot: DatabaseBot) -> String? { try? secrets.get(bot.keychainAccount) } + + func setPassword(_ p: String, for bot: DatabaseBot) { try? secrets.set(p, for: bot.keychainAccount) } + + func target(for bot: DatabaseBot) -> EngineTarget { + EngineTarget(connection: bot.connection, password: password(for: bot)) + } + + var groups: [(name: String, bots: [DatabaseBot])] { + let order = ["Production", "Staging", "Development", "Local", "Custom"] + let grouped = Dictionary(grouping: bots, by: \.groupName) + return grouped.keys.sorted { (order.firstIndex(of: $0) ?? 99, $0) < (order.firstIndex(of: $1) ?? 99, $1) } + .map { ($0, grouped[$0]!.sorted { $0.sortOrder < $1.sortOrder }) } + } + + // MARK: Inspection + + enum InspectionReason { case first, manual, scheduled, daily } + + func registerSchedule(_ bot: DatabaseBot) async { + guard !bot.isDemo else { return } + let paused = !bot.schedule.enabled || !settings.backgroundMonitoring + await scheduler.register(bot.id, interval: TimeInterval(bot.schedule.intervalSeconds), paused: paused) + } + + var monitoringPaused: Bool { !settings.backgroundMonitoring } + + func setMonitoringPaused(_ paused: Bool) { + settings.backgroundMonitoring = !paused + Task { + await scheduler.setGloballyPaused(paused) + for b in bots { await registerSchedule(b) } + } + } + + func runAllInspections() { for b in bots where !b.isDemo { Task { await inspect(b.id, reason: .manual) } } } + + private func scheduledInspection(_ id: UUID) async -> InspectionScheduler.Outcome { + await inspect(id, reason: .scheduled) ? .success : .failure + } + + /// Runs the engine for one bot. Returns false on failure. + @discardableResult + func inspect(_ id: UUID, reason: InspectionReason) async -> Bool { + guard let bot = bot(id) else { return false } + if bot.isDemo { + if reason == .manual, let rec = latest[id] { post(ReportComposer.healthReport(bot: bot, record: rec, previous: nil, firstRun: false, scheduled: false)) } + return true + } + guard let engine else { + post(errorMessage(id, engineProblem ?? .engineMissing(""), retry: nil)) + return false + } + guard !inspecting.contains(id) else { return true } + inspecting.insert(id) + mutate(id) { $0.status = .connecting } + defer { inspecting.remove(id) } + let started = Date() + do { + let ctx = try await engine.inspect(target(for: bot)) + isOffline = false + record(id, InspectionRecord(botID: id, startedAt: started, finishedAt: Date(), context: ctx), reason: reason) + return true + } catch { + let e = error as? EngineError ?? .failed(error.localizedDescription) + if case .connection(.unreachable, _) = e, !NetworkStatus.shared.isReachable { isOffline = true } + mutate(id) { $0.status = .unreachable; $0.lastSummary = e.title } + var ledger = ledgerFor(id) + if let n = NotificationPlanner.planFailure(botName: bot.displayName, error: e, ledger: &ledger, prefs: prefs(for: bot)) { + deliver(n, bot: bot, messageID: nil) + } + saveLedger(ledger, for: id) + // Only interrupt the conversation for failures the user asked for, or the first of an outage. + if reason != .scheduled || ledger.connectivityDown { post(errorMessage(id, e, retry: .healthCheck)) } + return false + } + } + + /// Stores a finished inspection and turns it into messages and notifications. + func record(_ id: UUID, _ rec: InspectionRecord, reason: InspectionReason) { + guard let bot = bot(id) else { return } + let prev = latest[id] + try? store.save(rec) + try? store.prune(botID: id, olderThan: Date().addingTimeInterval(-Double(bot.schedule.retentionDays) * 86400)) + previous[id] = prev + latest[id] = rec + let changes = prev.map { FindingChanges.compare(previous: $0.context.findings, current: rec.context.findings, ignoring: bot.schedule.ignoredFindingKeys) } + + var reportMessage: ChatMessage? + switch reason { + case .first, .manual, .daily: + let m = ReportComposer.healthReport(bot: bot, record: rec, previous: prev, firstRun: reason == .first, scheduled: reason == .daily) + post(m); reportMessage = m + case .scheduled: + for m in ReportComposer.proactive(bot: bot, changes: changes ?? .init(), at: rec.finishedAt) { post(m); reportMessage = reportMessage ?? m } + } + + var ledger = ledgerFor(id) + let planned = NotificationPlanner.plan(botName: bot.displayName, + changes: changes ?? FindingChanges.compare(previous: [], current: rec.context.findings, ignoring: bot.schedule.ignoredFindingKeys), + scoreBefore: prev?.score.value, scoreAfter: rec.score, ledger: &ledger, prefs: prefs(for: bot)) + if reason == .daily { + ledger.lastDailyReport = Date() + if !settings.disabledCategories.contains(.scheduledReport) { + deliver(PlannedNotification(category: .scheduledReport, severity: .info, title: "\(bot.displayName) — daily report", + body: "Health score \(rec.score.value)/100. \(rec.score.critical) critical, \(rec.score.warnings) warnings.", + dedupKey: "daily|\(Calendar.current.startOfDay(for: Date()).timeIntervalSince1970)"), + bot: bot, messageID: reportMessage?.id) + } + } + // The first report is in front of the user already; don't also ping them. + if reason != .first { for n in planned { deliver(n, bot: bot, messageID: reportMessage?.id) } } + saveLedger(ledger, for: id) + + let live = rec.context.findings.filter { !$0.isSuppressed && !bot.schedule.ignoredFindingKeys.contains($0.key) } + mutate(id) { + $0.lastInspectedAt = rec.finishedAt + $0.lastScore = rec.score.completeness == .unavailable ? nil : rec.score.value + $0.lastSummary = ReportComposer.sidebarSummary(record: rec, changes: changes) + $0.status = live.contains { $0.severity == .critical } ? .critical : (live.contains { $0.severity == .warn } ? .degraded : .healthy) + if !$0.schedule.enabled { $0.status = .paused } + } + } + + private func startDailyTimer() { + dailyTimer?.invalidate() + dailyTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in + let model = self + Task { @MainActor in model?.runDueDailyReports() } + } + } + + func runDueDailyReports(now: Date = Date()) { + guard settings.backgroundMonitoring else { return } + let cal = Calendar.current + for b in bots where !b.isDemo && b.schedule.enabled { + guard let hour = b.schedule.dailyReportHour, cal.component(.hour, from: now) >= hour else { continue } + let ledger = ledgerFor(b.id) + if let last = ledger.lastDailyReport, cal.isDate(last, inSameDayAs: now) { continue } + Task { await inspect(b.id, reason: .daily) } + } + } + + // MARK: Conversation + + func messages(for id: UUID) -> [ChatMessage] { conversations[id] ?? [] } + + func post(_ m: ChatMessage) { + conversations[m.botID, default: []].append(m) + try? store.append(m) + if m.botID != selection, m.role == .assistant { mutate(m.botID) { $0.unreadCount += 1 } } + scrollTarget = m.id + } + + func deleteMessage(_ m: ChatMessage) { + conversations[m.botID]?.removeAll { $0.id == m.id } + try? store.deleteMessage(m.id) + } + + func clearConversation(_ id: UUID) { + try? store.clearConversation(id) + conversations[id] = [] + } + + func markBotRead(_ id: UUID) { + if bot(id)?.unreadCount ?? 0 > 0 { mutate(id) { $0.unreadCount = 0 } } + } + + var isGenerating: Bool { selection.map { generating[$0] != nil } ?? false } + + /// A question typed into the composer. + func send(_ text: String, to id: UUID) { + let q = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !q.isEmpty, bot(id) != nil else { return } + let userMessage = ChatMessage(botID: id, role: .user, payload: .text(q)) + post(userMessage) + answer(userMessage) + } + + /// Answers through `pgbot ask`, which grounds the model on the engine's + /// deterministic findings and nothing else. + func answer(_ question: ChatMessage, consentGranted: Bool = false) { + guard case .text(let q) = question.payload, let bot = bot(question.botID) else { return } + let id = bot.id + if bot.isDemo { + post(ChatMessage(botID: id, role: .assistant, payload: .text( + "This is a demo database, so there's no live engine to ask. Connect a real database to ask questions grounded on its own findings."), + inReplyTo: question.id)) + return + } + let ai = settings.ai + let key = ai.provider.needsKey ? (try? secrets.get(SecretAccount.aiKey(ai.provider))) ?? nil : nil + if ai.provider.needsKey && (key ?? "").isEmpty { + post(ChatMessage(botID: id, role: .assistant, payload: .error( + title: "No AI provider configured", + detail: "Natural-language answers use your own AI provider. Deterministic diagnostics (the + menu) work without one.", + hint: "Add an API key in Settings → AI providers, or choose Ollama to keep everything on this Mac."), inReplyTo: question.id)) + return + } + if !ai.isLocal && !settings.aiConsents.contains(settings.consentKey(for: ai)) && !consentGranted { + pendingConsent = PendingConsent(botID: id, question: question.id.uuidString, ai: ai) + return + } + guard let engine else { post(errorMessage(id, engineProblem ?? .engineMissing(""), retry: nil)); return } + let target = target(for: bot) + generating[id] = Task { + defer { generating[id] = nil } + do { + let text = try await engine.ask(target, question: q, ai: ai, apiKey: key) + guard !Task.isCancelled else { return } + post(ChatMessage(botID: id, role: .assistant, payload: .text(text), inReplyTo: question.id, + modelName: ai.model.isEmpty ? ai.provider.label : ai.model)) + } catch is CancellationError { + post(ChatMessage(botID: id, role: .system, payload: .monitoringEvent("Stopped."), inReplyTo: question.id)) + } catch { + guard !Task.isCancelled else { + post(ChatMessage(botID: id, role: .system, payload: .monitoringEvent("Stopped."), inReplyTo: question.id)); return + } + let e = error as? EngineError ?? .aiFailed(error.localizedDescription) + post(ChatMessage(botID: id, role: .assistant, payload: .error(title: e.title, detail: e.detail, hint: e.hint), inReplyTo: question.id)) + } + } + } + + func grantConsent(_ c: PendingConsent) { + settings.aiConsents.insert(settings.consentKey(for: c.ai)) + pendingConsent = nil + if let m = messages(for: c.botID).first(where: { $0.id.uuidString == c.question }) { answer(m, consentGranted: true) } + } + + func stopGenerating(_ id: UUID) { generating[id]?.cancel() } + + func regenerate(_ answerMessage: ChatMessage) { + guard let qid = answerMessage.inReplyTo, let q = messages(for: answerMessage.botID).first(where: { $0.id == qid }) else { return } + answer(q) + } + + /// Plus-menu actions: deterministic engine output, no AI involved. + func run(_ action: QuickAction, on id: UUID) { + guard let bot = bot(id) else { return } + post(ChatMessage(botID: id, role: .user, payload: .text(action.label))) + let ctx = latest[id]?.context + func needInspection() -> Bool { + if ctx == nil { Task { await inspect(id, reason: .manual) }; return true } + return false + } + switch action { + case .healthCheck: + Task { await inspect(id, reason: .manual) } + case .queries: + if needInspection() { return } + post(.init(botID: id, role: .assistant, payload: ReportComposer.queriesTable(ctx!, title: "Most expensive queries by total time"))) + case .indexes: + if needInspection() { return } + post(.init(botID: id, role: .assistant, payload: ReportComposer.indexesTable(ctx!))) + let ixFindings = ctx!.findings.filter { $0.id.contains("index") && !$0.isSuppressed } + if !ixFindings.isEmpty { post(.init(botID: id, role: .assistant, payload: .findingsList(title: "Index findings", findings: ixFindings))) } + case .locks: + if needInspection() { return } + post(.init(botID: id, role: .assistant, payload: ReportComposer.locksTable(ctx!))) + case .replication: + if needInspection() { return } + post(.init(botID: id, role: .assistant, payload: ReportComposer.replicationTable(ctx!))) + case .connections: + if bot.isDemo { post(.init(botID: id, role: .assistant, payload: .text("Demo mode: live sessions aren't available for sample databases."))); return } + engineCall(id, retry: action) { e, t in .init(botID: id, role: .assistant, payload: ReportComposer.sessionsTable(try await e.activity(t))) } + case .logs: + route = .logs + case .explainSQL: + explainSQLDraft = "" + case .schema: + if needInspection() { return } + let tables = ctx!.tables?.top ?? [] + post(.init(botID: id, role: .assistant, payload: tables.isEmpty ? .text("No user tables were found.") + : .table(title: "Largest tables", columns: ["Table", "Size", "Rows", "Dead"], + rows: tables.map { [$0.id, Format.bytes($0.totalBytes), Format.count($0.liveTuples), Format.percent($0.deadRatio)] }))) + case .report: + if needInspection() { return } + let rec = latest[id]! + post(ReportComposer.healthReport(bot: bot, record: rec, previous: previous[id], firstRun: false, scheduled: false)) + case .whatChanged: + if bot.isDemo { post(.init(botID: id, role: .assistant, payload: .text("Demo mode: “what changed” needs real baselines from repeated inspections."))); return } + engineCall(id, retry: action) { e, t in .init(botID: id, role: .assistant, payload: .plan(sql: "", reading: try await e.diff(t, since: "24h"))) } + } + } + + // MARK: PSQL mode + + func isPSQL(_ id: UUID) -> Bool { psqlBots.contains(id) } + + func setPSQLMode(_ on: Bool, for id: UUID) { + guard on != isPSQL(id) else { return } + if on { + psqlBots.insert(id) + post(ChatMessage(botID: id, role: .system, payload: .monitoringEvent("PSQL mode · read-only — type SQL ending with ; or \\? for help"))) + } else { + psqlBots.remove(id) + post(ChatMessage(botID: id, role: .system, payload: .monitoringEvent("Back to chat"))) + } + } + + /// One line of console input: SQL or a psql meta-command. Everything that + /// reaches the database runs through `pgbot sql run` (READ ONLY, rolled back). + func runPSQL(_ raw: String, on id: UUID) { + let input = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !input.isEmpty, let bot = bot(id) else { return } + var history = psqlHistory[id] ?? [] + if history.last != input { history.append(input) } + psqlHistory[id] = Array(history.suffix(200)) + if !bot.isDemo { try? store.setValue(psqlHistory[id], for: "psqlHistory.\(id)") } + post(ChatMessage(botID: id, role: .user, payload: .psqlInput(input))) + + func notice(_ message: String, refusal: Bool = true) { + post(ChatMessage(botID: id, role: .assistant, payload: .psqlResult(PSQLResultPayload( + input: input, title: nil, + output: SQLRunOutput(results: [], error: SQLRunError(message: message, sqlstate: refusal ? "PGBOT" : nil), elapsedMS: 0), + expanded: psqlExpanded)))) + } + + let command = PSQL.parse(input) + switch command { + case .help: + post(ChatMessage(botID: id, role: .assistant, payload: .text(PSQL.helpText))) + return + case .quit: + setPSQLMode(false, for: id) + return + case .toggleExpanded(let v): + psqlExpanded = v ?? !psqlExpanded + post(ChatMessage(botID: id, role: .system, payload: .monitoringEvent("Expanded display is \(psqlExpanded ? "on" : "off")"))) + return + case .unsupported(_, let reason): + notice(reason) + return + case .sql, .meta: + break + } + let (sql, title): (String, String?) = { + if case .meta(let s, let t) = command { return (s, t) } + if case .sql(let s) = command { return (s, nil) } + return ("", nil) + }() + guard !bot.isDemo else { + notice("PSQL mode needs a live database — demo databases are sample data with no server behind them.") + return + } + guard let engine else { post(errorMessage(id, engineProblem ?? .engineMissing(""), retry: nil)); return } + let target = target(for: bot) + let expanded = psqlExpanded + generating[id] = Task { + defer { generating[id] = nil } + do { + let out = try await engine.runSQL(target, sql: sql, maxRows: 500) + guard !Task.isCancelled else { return } + post(ChatMessage(botID: id, role: .assistant, payload: .psqlResult( + PSQLResultPayload(input: input, title: title, output: out, expanded: expanded)))) + } catch is CancellationError { + post(ChatMessage(botID: id, role: .system, payload: .monitoringEvent("Query cancelled."))) + } catch { + post(errorMessage(id, error as? EngineError ?? .failed(error.localizedDescription), retry: nil)) + } + } + } + + func explain(sql: String, on id: UUID) { + explainSQLDraft = nil + let s = sql.trimmingCharacters(in: .whitespacesAndNewlines) + guard !s.isEmpty else { return } + post(ChatMessage(botID: id, role: .user, payload: .sql(title: "Explain this query", sql: s))) + guard bot(id)?.isDemo == false else { + post(.init(botID: id, role: .assistant, payload: .text("Demo mode: plans need a live database."))); return + } + engineCall(id, retry: nil) { e, t in .init(botID: id, role: .assistant, payload: .plan(sql: s, reading: try await e.explainSQL(t, sql: s))) } + } + + /// Hand a log line to the assistant, redacted first. + func explainLog(_ entry: LogEntry, botID: UUID) { + route = .chat + let redacted = Redactor.redactSQLLiterals([entry.severity + ": " + entry.message, entry.detail ?? ""].joined(separator: "\n")) + send(""" + Explain this PostgreSQL log entry: what happened, likely causes, the supporting evidence from your findings, \ + recommended actions, and whether more investigation is needed. + + \(redacted) + """, to: botID) + } + + private func engineCall(_ id: UUID, retry: QuickAction?, _ body: @escaping (DiagnosticEngine, EngineTarget) async throws -> ChatMessage) { + guard let bot = bot(id), let engine else { post(errorMessage(id, engineProblem ?? .engineMissing(""), retry: nil)); return } + let t = target(for: bot) + generating[id] = Task { + defer { generating[id] = nil } + do { let m = try await body(engine, t); if !Task.isCancelled { post(m) } } + catch is CancellationError {} + catch { post(errorMessage(id, error as? EngineError ?? .failed(error.localizedDescription), retry: retry)) } + } + } + + private func errorMessage(_ id: UUID, _ e: EngineError, retry: QuickAction?) -> ChatMessage { + ChatMessage(botID: id, role: .assistant, payload: .error(title: e.title, detail: e.detail, hint: e.hint)) + } + + // MARK: Notifications + + var unreadNotifications: Int { notifications.filter { !$0.read }.count } + + private func prefs(for bot: DatabaseBot) -> NotificationPlanner.Preferences { + .init(minimum: max(bot.schedule.notifyMinimum, settings.minimumSeverity), + notifyResolved: bot.schedule.notifyResolved, disabled: settings.disabledCategories) + } + + private func ledgerFor(_ id: UUID) -> AnnouncementLedger { store.value(AnnouncementLedger.self, for: "ledger.\(id)") ?? AnnouncementLedger() } + private func saveLedger(_ l: AnnouncementLedger, for id: UUID) { try? store.setValue(l, for: "ledger.\(id)") } + + private func deliver(_ p: PlannedNotification, bot: DatabaseBot, messageID: UUID?) { + let n = AppNotification(botID: bot.id, category: p.category, severity: p.severity, title: p.title, body: p.body, + messageID: messageID, dedupKey: p.dedupKey) + notifications.insert(n, at: 0) + try? store.save(n) + updateDockBadge() + // The in-app center always records it; the macOS banner respects the switches, + // the database's mute, and quiet hours (which critical alerts may break through). + guard settings.notificationsEnabled, settings.systemBanners, !bot.muted else { return } + let urgent = n.severity == .critical && settings.criticalBreaksQuietHours + if settings.quietHours.contains(Date()) && !urgent { return } + SystemNotifications.post(n, botName: bot.displayName, sound: settings.notificationSounds, preview: settings.showPreviews) + } + + /// Unread count on the Dock icon (Settings → Notifications → Badge). + func updateDockBadge() { + let unread = unreadNotifications + NSApp.dockTile.badgeLabel = settings.dockBadge && settings.notificationsEnabled && unread > 0 ? "\(unread)" : nil + } + + func markRead(_ n: AppNotification) { + guard let i = notifications.firstIndex(where: { $0.id == n.id }) else { return } + notifications[i].read = true + try? store.save(notifications[i]) + updateDockBadge() + } + + func markAllRead() { + for i in notifications.indices where !notifications[i].read { notifications[i].read = true; try? store.save(notifications[i]) } + updateDockBadge() + } + + func open(_ n: AppNotification) { + markRead(n) + selection = n.botID + route = .chat + showingNotifications = false + scrollTarget = n.messageID + } + + func open(notificationID: String) { + if let n = notifications.first(where: { $0.id.uuidString == notificationID }) { open(n) } + } + + func requestNotificationPermission() { SystemNotifications.requestAuthorization() } + + /// "Send test": a real system notification, so the user can check banners, + /// sounds and Focus settings. Returns a reason when it can't be delivered. + @discardableResult + func sendTestNotification() -> String? { + guard SystemNotifications.available else { return "System notifications need the bundled PGBot.app." } + guard settings.notificationsEnabled else { return "Notifications are turned off in PGBot." } + SystemNotifications.requestAuthorization() + SystemNotifications.postTest(sound: settings.notificationSounds) + return nil + } + + // MARK: Settings & system + + private func persistSettings(_ old: AppSettings) { + Theme.apply(settings) + if scenario == nil { try? realStore.setValue(settings, for: "settings") } + if old.enginePathOverride != settings.enginePathOverride { + let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("PGBot") + configureEngine(stateDirectory: support.appendingPathComponent("engine-state")) + } + if old.launchAtLogin != settings.launchAtLogin { LoginItem.set(settings.launchAtLogin) } + if old.dockBadge != settings.dockBadge || old.notificationsEnabled != settings.notificationsEnabled { updateDockBadge() } + if old.backgroundMonitoring != settings.backgroundMonitoring { + Task { await scheduler.setGloballyPaused(!settings.backgroundMonitoring) } + } + } + + func saveAPIKey(_ key: String, for provider: AIProviderKind) { + if key.isEmpty { try? secrets.delete(SecretAccount.aiKey(provider)) } else { try? secrets.set(key, for: SecretAccount.aiKey(provider)) } + } + + func hasAPIKey(_ provider: AIProviderKind) -> Bool { ((try? secrets.get(SecretAccount.aiKey(provider))) ?? nil)?.isEmpty == false } + + func deleteAllLocalData() { + for b in bots { try? secrets.delete(b.keychainAccount) } + for p in AIProviderKind.allCases { try? secrets.delete(SecretAccount.aiKey(p)) } + try? realStore.wipe() + settings = AppSettings() + bots = []; conversations = [:]; latest = [:]; previous = [:]; notifications = []; selection = nil + } + + private func observeSystem() { + // Capture the scheduler actor, not self: these run on the notification queue. + let scheduler: InspectionScheduler = self.scheduler + let ws = NSWorkspace.shared.notificationCenter + observers.append(ws.addObserver(forName: NSWorkspace.willSleepNotification, object: nil, queue: .main) { _ in + Task { await scheduler.willSleep() } + }) + observers.append(ws.addObserver(forName: NSWorkspace.didWakeNotification, object: nil, queue: .main) { _ in + Task { await scheduler.didWake() } + }) + } + + // MARK: Export + + func exportConversation(_ id: UUID) { + guard let bot = bot(id) else { return } + let f = DateFormatter(); f.dateStyle = .medium; f.timeStyle = .short + let text = messages(for: id).map { "[\(f.string(from: $0.createdAt))] \($0.role == .user ? "You" : "PGBot"): \($0.plainText)" } + .joined(separator: "\n\n") + FileExport.save(Data(text.utf8), suggestedName: "\(bot.displayName) conversation.txt") + } + + func exportInspection(_ id: UUID) { + guard let bot = bot(id), let rec = latest[id], let data = try? EngineJSON.encoder().encode(rec.context) else { return } + FileExport.save(data, suggestedName: "\(bot.displayName) inspection.json") + } +} + +// MARK: - Platform helpers + +enum FileExport { + @MainActor static func save(_ data: Data, suggestedName: String) { + let panel = NSSavePanel() + panel.nameFieldStringValue = suggestedName + panel.canCreateDirectories = true + if panel.runModal() == .OK, let url = panel.url { try? data.write(to: url, options: .atomic) } + } +} + +enum LoginItem { + static func set(_ on: Bool) { + guard Bundle.main.bundleIdentifier != nil else { return } + do { if on { try SMAppService.mainApp.register() } else { try SMAppService.mainApp.unregister() } } catch {} + } +} + +/// Network path monitoring, used to tell "you're offline" apart from "the database is down". +final class NetworkStatus: @unchecked Sendable { + static let shared = NetworkStatus() + private let monitor = NWPathMonitor() + private let lock = NSLock() + private var satisfied = true + var isReachable: Bool { lock.withLock { satisfied } } + private init() { + monitor.pathUpdateHandler = { [weak self] p in self?.lock.withLock { self?.satisfied = p.status == .satisfied } } + monitor.start(queue: DispatchQueue(label: "dev.pgbot.desktop.network")) + } +} + +/// Native Notification Center delivery. Only available when running as a +/// bundled .app (UNUserNotificationCenter requires a bundle identifier). +enum SystemNotifications { + static var available: Bool { Bundle.main.bundleIdentifier != nil } + + static func requestAuthorization() { + guard available else { return } + UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { _, _ in } + } + + static func postTest(sound: Bool) { + guard available else { return } + let c = UNMutableNotificationContent() + c.title = "🐘 PGBot · Test notification" + c.body = "Notifications are working. Findings, regressions and recoveries will appear like this." + if sound { c.sound = .default } + UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "test-\(UUID().uuidString)", content: c, trigger: nil)) + } + + enum Permission { case unknown, allowed, denied, notAsked } + + static func permission() async -> Permission { + guard available else { return .unknown } + switch await UNUserNotificationCenter.current().notificationSettings().authorizationStatus { + case .authorized, .provisional: return .allowed + case .denied: return .denied + case .notDetermined: return .notAsked + default: return .unknown + } + } + + static func openSystemSettings() { + let id = Bundle.main.bundleIdentifier ?? "dev.pgbot.desktop" + if let url = URL(string: "x-apple.systempreferences:com.apple.Notifications-Settings.extension?id=\(id)") { + NSWorkspace.shared.open(url) + } + } + + static func post(_ n: AppNotification, botName: String, sound: Bool, preview: Bool = true) { + guard available else { return } + let c = UNMutableNotificationContent() + // Without previews, the banner says only which database needs a look. + c.title = preview ? n.title : "🐘 \(botName)" + c.body = preview ? n.body : (n.category == .resolved ? "An issue was resolved." : "New activity — open PGBot to see details.") + c.threadIdentifier = n.botID.uuidString + c.userInfo = ["notificationID": n.id.uuidString] + if sound && n.severity != .info { c.sound = .default } + c.interruptionLevel = n.severity == .critical ? .timeSensitive : .active + UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: n.id.uuidString, content: c, trigger: nil)) + } +} diff --git a/desktop/macos/Sources/PGBot/App/AppSettings.swift b/desktop/macos/Sources/PGBot/App/AppSettings.swift new file mode 100644 index 0000000..5e32a3c --- /dev/null +++ b/desktop/macos/Sources/PGBot/App/AppSettings.swift @@ -0,0 +1,181 @@ +import PGBotKit +import SwiftUI + +/// Global preferences, persisted in the local store (no secrets here). +struct AppSettings: Codable, Equatable { + enum Appearance: String, Codable, CaseIterable { case system, light, dark } + + var appearance: Appearance = .dark + var avatarStyle: AvatarStyle = .emoji + var accent: AccentChoice = .system + var textSize: TextSize = .standard + var density: Density = .comfortable + var bubbleStyle: BubbleStyle = .bubbles + var showTimestamps = true + var sendWithReturn = true + var showPinnedBots = true + var groupByEnvironment = true + var showSidebarPreviews = true + var restoreLastSelection = true + // Defaults for newly added databases + var defaultEnvironment: DatabaseEnvironment = .production + var defaultSSLMode: SSLMode = .prefer + var defaultConnectTimeout = 10 + var defaultAvatarShape: AvatarShape = .roundedSquare + /// nil = pick a random color for each new bot. + var defaultAvatarColor: BotColor? = nil + var showMenuBarIcon = true + var launchAtLogin = false + var backgroundMonitoring = true + var defaultIntervalSeconds = 3600 + var defaultDailyReportHour: Int? = 9 + var defaultRetentionDays = 30 + var notificationsEnabled = true + var notificationSounds = true + /// macOS banners in Notification Center (off = in-app notification center only). + var systemBanners = true + /// Show the finding in the banner; off shows only "New finding on ". + var showPreviews = true + /// Unread count on the Dock icon. + var dockBadge = true + /// Critical findings and outages still alert during quiet hours. + var criticalBreaksQuietHours = true + var animateAvatars = true + var quietHours = QuietHours() + var minimumSeverity: Severity = .warn + var disabledCategories: Set = [] + var ai = AIConfiguration() + /// Providers (by engine name + host) the user has agreed to send findings to. + var aiConsents: Set = [] + var enginePathOverride = "" + var telemetryOptIn = false + var bands = HealthBands() + var pinnedSectionCollapsed = false + var collapsedGroups: Set = [] + + var colorScheme: ColorScheme? { + switch appearance { case .system: nil; case .light: .light; case .dark: .dark } + } + + func consentKey(for ai: AIConfiguration) -> String { "\(ai.provider.engineName)@\(ai.effectiveBaseURL ?? "default")" } + + /// Restores only the look-and-feel options, keeping everything else. + mutating func resetAppearance() { + let d = AppSettings() + appearance = d.appearance; avatarStyle = d.avatarStyle; accent = d.accent; textSize = d.textSize; density = d.density + bubbleStyle = d.bubbleStyle; showTimestamps = d.showTimestamps; sendWithReturn = d.sendWithReturn + animateAvatars = d.animateAvatars; showPinnedBots = d.showPinnedBots; groupByEnvironment = d.groupByEnvironment; showSidebarPreviews = d.showSidebarPreviews + } + + /// Decodes saved settings on top of the current defaults, so options added + /// in a newer version get their default instead of discarding the file. + /// These settings with some keys replaced from a JSON object (launch scenarios). + func overlaid(with json: Data) -> AppSettings { + guard let current = try? JSONEncoder().encode(self), + let base = try? JSONSerialization.jsonObject(with: current) as? [String: Any], + let extra = try? JSONSerialization.jsonObject(with: json) as? [String: Any], + let merged = try? JSONSerialization.data(withJSONObject: base.merging(extra) { $1 }), + let out = try? JSONDecoder().decode(AppSettings.self, from: merged) else { return self } + return out + } + + static func load(_ data: Data?) -> AppSettings { + guard let data, + let stored = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let defaultsData = try? JSONEncoder().encode(AppSettings()), + let defaults = try? JSONSerialization.jsonObject(with: defaultsData) as? [String: Any], + let merged = try? JSONSerialization.data(withJSONObject: defaults.merging(stored) { _, saved in saved }) + else { return AppSettings() } + return (try? JSONDecoder().decode(AppSettings.self, from: merged)) ?? AppSettings() + } +} + +enum AccentChoice: String, Codable, CaseIterable, Identifiable { + case system, blue, purple, pink, red, orange, yellow, green, teal, graphite + var id: String { rawValue } + var label: String { self == .system ? "System" : rawValue.capitalized } + var color: Color { + switch self { + case .system: .accentColor + case .blue: Color(red: 0.20, green: 0.48, blue: 0.98) + case .purple: Color(red: 0.56, green: 0.36, blue: 0.95) + case .pink: Color(red: 0.93, green: 0.30, blue: 0.60) + case .red: Color(red: 0.92, green: 0.27, blue: 0.27) + case .orange: Color(red: 0.96, green: 0.50, blue: 0.10) + case .yellow: Color(red: 0.90, green: 0.68, blue: 0.05) + case .green: Color(red: 0.18, green: 0.68, blue: 0.38) + case .teal: Color(red: 0.10, green: 0.66, blue: 0.64) + case .graphite: Color(red: 0.45, green: 0.47, blue: 0.51) + } + } +} + +enum TextSize: String, Codable, CaseIterable, Identifiable { + case small, standard, large, extraLarge + var id: String { rawValue } + var label: String { switch self { case .small: "Small"; case .standard: "Default"; case .large: "Large"; case .extraLarge: "Extra Large" } } + var scale: CGFloat { switch self { case .small: 0.9; case .standard: 1; case .large: 1.12; case .extraLarge: 1.25 } } +} + +enum Density: String, Codable, CaseIterable, Identifiable { + case compact, comfortable + var id: String { rawValue } + var label: String { rawValue.capitalized } +} + +enum BubbleStyle: String, Codable, CaseIterable, Identifiable { + case bubbles, plain + var id: String { rawValue } + var label: String { self == .bubbles ? "Bubbles" : "Plain text" } +} + +enum DetailRoute: Equatable { case chat, metrics, logs } + +enum AuthPhase: Equatable { + case restoring + case signedOut(error: String?) + case signingIn(AuthProvider) + case signedIn(AuthenticationSession) +} + +/// The deterministic actions behind the composer's plus menu. +enum QuickAction: String, CaseIterable, Identifiable { + case healthCheck, queries, indexes, connections, locks, replication, logs, explainSQL, schema, report, whatChanged + var id: String { rawValue } + var label: String { + switch self { + case .healthCheck: "Run health check" + case .queries: "Analyze queries" + case .indexes: "Analyze indexes" + case .connections: "Show active connections" + case .locks: "Show database locks" + case .replication: "Analyze replication" + case .logs: "Show database logs" + case .explainSQL: "Explain SQL…" + case .schema: "Show schema" + case .report: "Generate database report" + case .whatChanged: "What changed since yesterday?" + } + } + var symbol: String { + switch self { + case .healthCheck: "stethoscope" + case .queries: "bolt.horizontal" + case .indexes: "list.bullet.indent" + case .connections: "person.2" + case .locks: "lock" + case .replication: "arrow.triangle.2.circlepath" + case .logs: "doc.plaintext" + case .explainSQL: "text.magnifyingglass" + case .schema: "tablecells" + case .report: "doc.richtext" + case .whatChanged: "clock.arrow.circlepath" + } + } +} + +enum AvatarStyle: String, Codable, CaseIterable, Identifiable { + case emoji, mascot + var id: String { rawValue } + var label: String { self == .emoji ? "🐘 Elephant" : "Slonic mascot" } +} diff --git a/desktop/macos/Sources/PGBot/App/PGBotApp.swift b/desktop/macos/Sources/PGBot/App/PGBotApp.swift new file mode 100644 index 0000000..dfd1092 --- /dev/null +++ b/desktop/macos/Sources/PGBot/App/PGBotApp.swift @@ -0,0 +1,120 @@ +import AppKit +import PGBotKit +import SwiftUI +import UserNotifications + +@main +struct PGBotApp: App { + @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate + @State private var model = AppModel() + + var body: some Scene { + Window("PGBot", id: "main") { + RootView() + // Text size and accent are read from Theme globals; rebuilding on change applies them everywhere. + .id("\(model.settings.textSize.rawValue)-\(model.settings.accent.rawValue)-\(model.settings.bubbleStyle.rawValue)-\(model.settings.avatarStyle.rawValue)") + .environment(model) + .tint(model.settings.accent.color) + .preferredColorScheme(model.settings.colorScheme) + .task { + delegate.model = model + await model.start() + } + } + .defaultSize(width: 1180, height: 780) + .windowStyle(.hiddenTitleBar) + .commands { AppCommands(model: model) } + + Window("PGBot Settings", id: "settings") { + AppSettingsView() + .environment(model) + .tint(model.settings.accent.color) + .preferredColorScheme(model.settings.colorScheme) + } + .windowResizability(.contentSize) + .defaultPosition(.center) + + // Read-only binding: SwiftUI calls the setter while inserting the item, and + // writing settings from there re-evaluates this body in a loop. + MenuBarExtra(isInserted: Binding(get: { model.settings.showMenuBarIcon }, set: { _ in })) { + MenuBarContent().environment(model) + } label: { + Image(systemName: menuBarSymbol) + } + .menuBarExtraStyle(.window) + } + + private var menuBarSymbol: String { + if model.bots.contains(where: { $0.status == .critical || $0.status == .unreachable }) { return "exclamationmark.circle.fill" } + if model.bots.contains(where: { $0.status == .degraded }) { return "exclamationmark.circle" } + return "circle.hexagonpath" + } +} + +/// `Commands.body` is nonisolated in the macOS 14 SDK, but menu actions and +/// their state reads always happen on the main thread — so each touch of the +/// model asserts that instead of hopping. +struct AppCommands: Commands { + let model: AppModel + @Environment(\.openWindow) private var openWindow + + private func onMain(_ body: @MainActor () -> T) -> T { MainActor.assumeIsolated(body) } + + var body: some Commands { + let signedIn = onMain { model.session != nil } + let hasSelection = onMain { model.selection != nil } + let paused = onMain { model.monitoringPaused } + CommandGroup(replacing: .appSettings) { + Button("Settings…") { onMain { openWindow(id: "settings") } }.keyboardShortcut(",") + } + CommandGroup(replacing: .newItem) { + Button("Add Database…") { onMain { openWindow(id: "main"); model.showingAddDatabase = true } } + .keyboardShortcut("n") + .disabled(!signedIn) + } + CommandMenu("Database") { + Button("Search Databases") { onMain { model.showingSearch = true } }.keyboardShortcut("k") + Divider() + Button("Run Inspection") { onMain { if let id = model.selection { Task { await model.inspect(id, reason: .manual) } } } } + .keyboardShortcut("r").disabled(!hasSelection) + Button("Run All Inspections") { onMain { model.runAllInspections() } }.keyboardShortcut("r", modifiers: [.command, .shift]) + Divider() + Button("Conversation") { onMain { model.route = .chat } }.keyboardShortcut("1") + Button("Metrics") { onMain { model.route = .metrics } }.keyboardShortcut("2") + Button("Logs") { onMain { model.route = .logs } }.keyboardShortcut("3") + Button("PSQL Mode") { onMain { if let id = model.selection { model.route = .chat; model.setPSQLMode(!model.isPSQL(id), for: id) } } } + .keyboardShortcut("p", modifiers: [.command, .shift]).disabled(!hasSelection) + Divider() + Button("Notifications") { onMain { model.showingNotifications.toggle() } }.keyboardShortcut("n", modifiers: [.command, .shift]) + Button(paused ? "Resume Monitoring" : "Pause Monitoring") { onMain { model.setMonitoringPaused(!model.monitoringPaused) } } + } + } +} + +/// Keeps monitoring alive with the window closed (when the menu bar icon is on) +/// and routes notification clicks back into the app. +final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { + weak var model: AppModel? + + func applicationDidFinishLaunching(_ notification: Notification) { + if SystemNotifications.available { UNUserNotificationCenter.current().delegate = self } + // Started from `swift run` (no bundle) the process is not a regular app yet. + if Bundle.main.bundleIdentifier == nil { NSApp.setActivationPolicy(.regular); NSApp.activate(ignoringOtherApps: true) } + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + MainActor.assumeIsolated { !(model?.settings.showMenuBarIcon ?? false) } + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { + let id = response.notification.request.content.userInfo["notificationID"] as? String + await MainActor.run { + NSApp.activate(ignoringOtherApps: true) + if let id { model?.open(notificationID: id) } + } + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { + [.banner, .list, .sound] + } +} diff --git a/desktop/macos/Sources/PGBot/Components/ElephantAvatar.swift b/desktop/macos/Sources/PGBot/Components/ElephantAvatar.swift new file mode 100644 index 0000000..7954b90 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Components/ElephantAvatar.swift @@ -0,0 +1,129 @@ +import PGBotKit +import SwiftUI + +/// A bot's avatar. Default style (design spec): the bot's color as a circle or a +/// softly rounded square tilted −8°, with 🐘 on it; the neutral color carries a +/// database icon instead. The flat "Slonic" mascot is the alternative style +/// (Settings → Appearance → Avatars). +@MainActor struct ElephantAvatar: View { + var color: BotColor + var shape: AvatarShape = .roundedSquare + var size: CGFloat = 36 + + @State private var hovering = false + @State private var wiggles = 0 + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + private struct Motion { var angle: Double = 0; var lift: CGFloat = 0 } + + var body: some View { + Group { + if Theme.avatarStyle == .emoji { emojiAvatar } else { mascot } + } + .frame(width: size, height: size) + // A little "hello" when the pointer arrives: hop, wiggle, settle. + .keyframeAnimator(initialValue: Motion(), trigger: wiggles) { content, m in + content.rotationEffect(.degrees(m.angle)).offset(y: m.lift) + } keyframes: { _ in + KeyframeTrack(\.angle) { + SpringKeyframe(-9, duration: 0.12) + SpringKeyframe(7, duration: 0.14) + SpringKeyframe(-3, duration: 0.12) + SpringKeyframe(0, duration: 0.22) + } + KeyframeTrack(\.lift) { + SpringKeyframe(-max(2, size * 0.08), duration: 0.14) + SpringKeyframe(0, duration: 0.4, spring: .bouncy) + } + } + .scaleEffect(hovering && animates ? 1.06 : 1) + .animation(.spring(response: 0.3, dampingFraction: 0.6), value: hovering) + .onHover { inside in + hovering = inside + if inside && animates { wiggles += 1 } + } + .accessibilityHidden(true) + } + + private var animates: Bool { Theme.animateAvatars && !reduceMotion && size >= 20 } + + private var emojiAvatar: some View { + let fill = color.color + let glyph = Group { + if color == .black { + Image(systemName: "cylinder.split.1x2").font(.system(size: size * 0.40, weight: .regular)).foregroundStyle(Color(nsColor: hex(0xd0d0d0))) + } else { + Text("🐘").font(.system(size: size * 0.46)) + } + } + return ZStack { + if shape == .circle { + Circle().fill(fill) + .overlay(Circle().strokeBorder(Color.white.opacity(color == .black ? 0.08 : 0))) + glyph + } else { + ZStack { + RoundedRectangle(cornerRadius: size * 0.31, style: .continuous).fill(fill) + .overlay(RoundedRectangle(cornerRadius: size * 0.31, style: .continuous).strokeBorder(Color.white.opacity(color == .black ? 0.08 : 0))) + glyph + } + .rotationEffect(.degrees(-8)) + .scaleEffect(0.94) // keep the tilted corners inside the frame + } + } + } + + private var mascot: some View { + let c = color.color + let s = size + return ZStack { + ear(c).frame(width: s * 0.34, height: s * 0.44).offset(x: -s * 0.30, y: -s * 0.04) + ear(c).frame(width: s * 0.34, height: s * 0.44).offset(x: s * 0.30, y: -s * 0.04) + head(c).frame(width: s * 0.74, height: s * 0.70).offset(y: s * 0.04) + HStack(spacing: s * 0.085) { eye(s); eye(s) } + .rotationEffect(.degrees(10)) + .offset(x: s * 0.06, y: -s * 0.01) + } + .rotationEffect(.degrees(-9)) + } + + @ViewBuilder private func head(_ c: Color) -> some View { + if shape == .circle { + Ellipse().fill(c) + } else { + RoundedRectangle(cornerRadius: size * 0.24, style: .continuous).fill(c) + } + } + + private func ear(_ c: Color) -> some View { + ZStack { + Ellipse().fill(c) + Ellipse().fill(Color.black.opacity(0.14)) + } + } + + private func eye(_ s: CGFloat) -> some View { + Capsule().fill(Color.white).frame(width: s * 0.072, height: s * 0.16) + } +} + +/// The product mark. +@MainActor struct PGBotLogo: View { + var size: CGFloat = 72 + var body: some View { ElephantAvatar(color: .blue, shape: .roundedSquare, size: size) } +} + +@MainActor struct BotAvatarView: View { + let bot: DatabaseBot + var size: CGFloat = 32 + var showsStatus = false + var body: some View { + ElephantAvatar(color: bot.avatar.color, shape: bot.avatar.shape, size: size) + .overlay(alignment: .bottomTrailing) { + // Only problems earn a dot; healthy bots stay clean. + if showsStatus && [.degraded, .critical, .unreachable].contains(bot.status) { + StatusDot(status: bot.status, size: max(9, size * 0.24)).offset(x: 1, y: 1) + } + } + } +} diff --git a/desktop/macos/Sources/PGBot/Components/HealthScoreView.swift b/desktop/macos/Sources/PGBot/Components/HealthScoreView.swift new file mode 100644 index 0000000..5fa6de0 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Components/HealthScoreView.swift @@ -0,0 +1,78 @@ +import PGBotKit +import SwiftUI + +/// The reusable health score: a large number, its band color, the change since +/// the previous inspection, and finding counts. Shows "Incomplete" or +/// "Unavailable" instead of a reassuring number when the engine couldn't see enough. +@MainActor struct HealthScoreView: View { + let score: HealthScore + var previous: Int? + var resolved: Int = 0 + var inspectedAt: Date? + var bands = HealthBands() + var compact = false + + var body: some View { + let band = bands.band(for: score) + HStack(alignment: .center, spacing: Space.l) { + VStack(alignment: .leading, spacing: 2) { + if score.completeness == .unavailable { + Text("—").font(.sys(size: compact ? 28 : 40, weight: .semibold, design: .rounded)) + Text("Health score unavailable").font(.callout).foregroundStyle(.secondary) + } else { + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text("\(score.value)") + .font(.sys(size: compact ? 30 : 44, weight: .semibold, design: .rounded)) + .foregroundStyle(band.color) + .contentTransition(.numericText()) + Text("/100").font(.sys(size: compact ? 14 : 17, weight: .medium, design: .rounded)).foregroundStyle(.secondary) + if let d = delta, d != 0 { + Label("\(d > 0 ? "+" : "")\(d)", systemImage: d > 0 ? "arrow.up.right" : "arrow.down.right") + .font(.caption.weight(.semibold)) + .foregroundStyle(d > 0 ? .green : .orange) + .padding(.leading, 6) + .help("Change since the previous inspection") + } + } + HStack(spacing: 6) { + Text("Health score").font(.callout).foregroundStyle(.secondary) + if score.completeness == .partial { + Text("Incomplete").font(.caption2.weight(.semibold)) + .padding(.horizontal, 6).padding(.vertical, 1) + .background(Color.orange.opacity(0.15), in: Capsule()).foregroundStyle(.orange) + .help(score.gaps.joined(separator: "\n")) + } + } + } + } + if !compact { + Divider().frame(height: 44) + HStack(spacing: Space.l) { + counter(score.critical, "Critical", .red) + counter(score.warnings, "Warnings", .orange) + counter(resolved, "Resolved", .green) + } + Spacer(minLength: 0) + if let at = inspectedAt { + VStack(alignment: .trailing, spacing: 2) { + Text("Last inspection").font(.caption).foregroundStyle(.secondary) + Text(at, style: .relative).font(.caption.monospacedDigit()) + Text(" ago").font(.caption) + } + .foregroundStyle(.secondary) + } + } + } + .accessibilityElement(children: .combine) + .accessibilityLabel(score.completeness == .unavailable ? "Health score unavailable" + : "Health score \(score.value) out of 100, \(score.critical) critical, \(score.warnings) warnings") + } + + private var delta: Int? { previous.map { score.value - $0 } } + + private func counter(_ n: Int, _ label: String, _ color: Color) -> some View { + VStack(alignment: .leading, spacing: 1) { + Text("\(n)").font(.title3.weight(.semibold).monospacedDigit()).foregroundStyle(n > 0 ? color : .primary) + Text(label).font(.caption).foregroundStyle(.secondary) + } + } +} diff --git a/desktop/macos/Sources/PGBot/Components/MessageView.swift b/desktop/macos/Sources/PGBot/Components/MessageView.swift new file mode 100644 index 0000000..1683d13 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Components/MessageView.swift @@ -0,0 +1,521 @@ +import AppKit +import Charts +import PGBotKit +import SwiftUI + +/// One message. PGBot speaks in soft gray bubbles (no avatar — the bot is in +/// the header); the user's messages sit on the right in a slightly darker +/// bubble. Copy/regenerate appear on hover. +@MainActor struct MessageView: View { + @Environment(AppModel.self) private var model + let message: ChatMessage + let bot: DatabaseBot + @State private var hovering = false + + var body: some View { + Group { + switch message.role { + case .user: userBubble + case .system: systemEvent + case .assistant: assistant + } + } + .onHover { hovering = $0 } + } + + /// Bot bubbles hug their content up to ~78% of the column, user bubbles ~70% (spec). + static let botMaxWidth: CGFloat = readableWidth * 0.78 + static let userMaxWidth: CGFloat = readableWidth * 0.70 + + private var userBubble: some View { + let compact = model.settings.density == .compact + return VStack(alignment: .trailing, spacing: 4) { + if case .sql(_, let sql) = message.payload { + SQLBlock(sql: sql).frame(maxWidth: Self.userMaxWidth) + } else if case .psqlInput(let input) = message.payload { + PSQLInputBubble(input: input, database: bot.connection.database).frame(maxWidth: readableWidth * 0.85, alignment: .trailing) + } else { + Text(message.plainText) + .font(Typo.body).lineSpacing(2).textSelection(.enabled) + .foregroundStyle(Palette.userText) + .padding(.horizontal, compact ? 14 : 16).padding(.vertical, compact ? 8 : 10) + .background(Palette.userBubble, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + .frame(maxWidth: Self.userMaxWidth, alignment: .trailing) + } + MessageActions(message: message).opacity(hovering ? 1 : 0) + } + .frame(maxWidth: .infinity, alignment: .trailing) + .help(message.createdAt.formatted(date: .abbreviated, time: .shortened)) + .contextMenu { copyItem } + } + + @ViewBuilder private var systemEvent: some View { + HStack(spacing: 6) { + switch message.payload { + case .connectionEvent(let s, let ok): + Image(systemName: ok ? "checkmark.circle.fill" : "xmark.circle.fill").foregroundStyle(ok ? .green : .red) + Text(s) + default: + Text(message.plainText) + } + } + .font(Typo.small).foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + } + + private var assistant: some View { + let plain = model.settings.bubbleStyle == .plain + let compact = model.settings.density == .compact + let isCard: Bool = { if case .text = message.payload { return false }; return true }() + let wide: Bool = { if case .psqlResult = message.payload { return true }; return false }() + return VStack(alignment: .leading, spacing: 4) { + content + .font(Typo.body) + .padding(.horizontal, plain ? 2 : (compact ? 14 : (isCard ? 18 : 16))) + .padding(.vertical, plain ? 2 : (compact ? 9 : (isCard ? 16 : 11))) + .background(plain ? .clear : Palette.bubble, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + .frame(maxWidth: wide ? .infinity : Self.botMaxWidth, alignment: .leading) + HStack(spacing: 6) { + MessageActions(message: message) + if let m = message.modelName, m != "demo" { Text(m).font(Typo.micro).foregroundStyle(.tertiary) } + } + .padding(.leading, 8) + .opacity(hovering ? 1 : 0) + } + .frame(maxWidth: .infinity, alignment: .leading) + .help(message.createdAt.formatted(date: .abbreviated, time: .shortened)) + .contextMenu { copyItem } + } + + @ViewBuilder private var content: some View { + switch message.payload { + case .text(let s): MarkdownText(source: s) + case .healthReport(let r): HealthReportCard(report: r, bot: bot) + case .finding(let f, let change): FindingCard(finding: f, change: change, bot: bot, standalone: true) + case .findingsList(let title, let fs): + VStack(alignment: .leading, spacing: 10) { + Text(title).font(Typo.bodyEmphasis) + ForEach(fs, id: \.key) { FindingCard(finding: $0, change: nil, bot: bot) } + } + case .sql(let title, let sql): + VStack(alignment: .leading, spacing: 10) { Text(title).font(Typo.bodyEmphasis); SQLBlock(sql: sql) } + case .plan(let sql, let reading): + VStack(alignment: .leading, spacing: 10) { + if !sql.isEmpty { SQLBlock(sql: sql) } + PlanBlock(text: reading) + } + case .table(let title, let cols, let rows): TableCard(title: title, columns: cols, rows: rows, framed: false) + case .metric(let key, let points): MiniChart(metric: key, points: points) + case .resolved(let fs): + VStack(alignment: .leading, spacing: 8) { + Text("✅ Issue resolved").font(Typo.bodyEmphasis) + ForEach(fs, id: \.key) { Text($0.title).foregroundStyle(Palette.muted) } + } + case .error(let title, let detail, let hint): ErrorContent(title: title, detail: detail, hint: hint, message: message) + case .connectionEvent(let s, _), .monitoringEvent(let s): Text(s).foregroundStyle(.secondary) + case .psqlInput(let s): Text(s).font(.sys(size: 13.5, design: .monospaced)) + case .psqlResult(let r): PSQLResultView(payload: r) + } + } + + private var copyItem: some View { Button("Copy Message") { Pasteboard.copy(message.plainText) } } +} + +@MainActor struct MessageActions: View { + @Environment(AppModel.self) private var model + let message: ChatMessage + @State private var copied = false + var body: some View { + HStack(spacing: 2) { + small(copied ? "checkmark" : "doc.on.doc", "Copy") { + Pasteboard.copy(message.plainText); copied = true + DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { copied = false } + } + if message.role == .assistant && message.inReplyTo != nil { + small("arrow.clockwise", "Regenerate") { model.regenerate(message) } + .disabled(model.generating[message.botID] != nil) + } + } + } + private func small(_ s: String, _ help: String, _ a: @escaping () -> Void) -> some View { + Button(action: a) { Image(systemName: s).font(.sys(size: 11.5)).frame(width: 24, height: 20) } + .buttonStyle(.plain).foregroundStyle(.secondary).hoverHighlight(cornerRadius: 6).help(help).accessibilityLabel(help) + } +} + +enum Pasteboard { + static func copy(_ s: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(s, forType: .string) + } +} + +// MARK: - Markdown + +/// Block-level Markdown: paragraphs, headings, lists and fenced code (SQL is +/// highlighted). Inline styling uses Foundation's Markdown parser. +@MainActor struct MarkdownText: View { + let source: String + + enum Block: Hashable { case heading(Int, String), paragraph(String), bullet(String, String), code(String, String) } + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + ForEach(Array(blocks.enumerated()), id: \.offset) { _, b in + switch b { + case .heading(let level, let s): + inline(s).font(level <= 2 ? Typo.title : Typo.bodyEmphasis).padding(.top, 2) + case .paragraph(let s): inline(s) + case .bullet(let marker, let s): + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(marker).foregroundStyle(.secondary).frame(minWidth: 12, alignment: .trailing) + inline(s) + } + case .code(let lang, let s): + if lang.isEmpty || lang.lowercased() == "sql" { SQLBlock(sql: s) } else { PlanBlock(text: s) } + } + } + } + .lineSpacing(3) + .textSelection(.enabled) + } + + private func inline(_ s: String) -> Text { + guard var a = try? AttributedString(markdown: s, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)) else { return Text(s) } + // `code` spans (table and column names) read as links-colored identifiers, per the spec. + for run in a.runs where run.inlinePresentationIntent?.contains(.code) == true { + a[run.range].foregroundColor = Palette.link + } + return Text(a) + } + + var blocks: [Block] { + var out: [Block] = [] + var para: [String] = [] + var inCode = false, lang = "", code: [String] = [] + func flush() { if !para.isEmpty { out.append(.paragraph(para.joined(separator: " "))); para = [] } } + for raw in source.components(separatedBy: "\n") { + let line = raw.trimmingCharacters(in: .whitespaces) + if line.hasPrefix("```") { + if inCode { out.append(.code(lang, code.joined(separator: "\n"))); code = []; inCode = false } + else { flush(); inCode = true; lang = String(line.dropFirst(3)) } + continue + } + if inCode { code.append(raw); continue } + if line.isEmpty { flush(); continue } + if let m = line.firstMatch(of: #/^(#{1,6})\s+(.*)$/#) { flush(); out.append(.heading(m.1.count, String(m.2))); continue } + if let m = line.firstMatch(of: #/^[-*•]\s+(.*)$/#) { flush(); out.append(.bullet("•", String(m.1))); continue } + if let m = line.firstMatch(of: #/^(\d+)[.)]\s+(.*)$/#) { flush(); out.append(.bullet("\(m.1).", String(m.2))); continue } + para.append(line) + } + if inCode { out.append(.code(lang, code.joined(separator: "\n"))) } + flush() + return out + } +} + +// MARK: - SQL & plans + +@MainActor struct SQLBlock: View { + let sql: String + @State private var copied = false + var body: some View { + ZStack(alignment: .topTrailing) { + ScrollView(.horizontal, showsIndicators: false) { + Text(SQLHighlighter.highlight(sql)).font(.sys(size: 13, design: .monospaced)) + .lineSpacing(2).textSelection(.enabled).padding(14).padding(.trailing, 28) + } + Button { + Pasteboard.copy(sql); copied = true + DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { copied = false } + } label: { + Image(systemName: copied ? "checkmark" : "doc.on.doc").font(.sys(size: 11.5)).padding(7) + } + .buttonStyle(.plain).foregroundStyle(.secondary).help("Copy SQL").accessibilityLabel("Copy SQL").padding(4) + } + .background(Palette.inset, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } +} + +enum SQLHighlighter { + static let keywords: Set = [ + "select", "from", "where", "and", "or", "not", "in", "is", "null", "join", "left", "right", "inner", "outer", "on", + "group", "by", "order", "having", "limit", "offset", "as", "distinct", "insert", "into", "values", "update", "set", + "delete", "create", "index", "table", "drop", "alter", "add", "concurrently", "if", "exists", "with", "union", "all", + "case", "when", "then", "else", "end", "asc", "desc", "returning", "grant", "revoke", "role", "to", "vacuum", "analyze", + "explain", "begin", "commit", "rollback", "like", "ilike", "between", "count", "sum", "avg", "min", "max", "now", + ] + + static func highlight(_ sql: String) -> AttributedString { + var out = AttributedString() + let pattern = #/('(?:[^']|'')*')|(--[^\n]*)|(\$\d+)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*)|(\s+)|(.)/# + for m in sql.matches(of: pattern) { + var piece = AttributedString(String(m.output.0)) + if m.output.1 != nil { piece.foregroundColor = .init(nsColor: .systemRed) } + else if m.output.2 != nil { piece.foregroundColor = .init(nsColor: .secondaryLabelColor) } + else if m.output.3 != nil || m.output.4 != nil { piece.foregroundColor = .init(nsColor: .systemOrange) } + else if let w = m.output.5, keywords.contains(w.lowercased()) { piece.foregroundColor = .init(nsColor: .systemPurple) } + out += piece + } + return out + } +} + +@MainActor struct PlanBlock: View { + let text: String + var body: some View { + ScrollView(.horizontal) { + Text(text.trimmingCharacters(in: .whitespacesAndNewlines)) + .font(.sys(size: 12, design: .monospaced)).textSelection(.enabled) + .padding(14).fixedSize(horizontal: true, vertical: false) + } + .frame(maxHeight: 420) + .background(Palette.inset, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .overlay(alignment: .topTrailing) { + Button { Pasteboard.copy(text) } label: { Image(systemName: "doc.on.doc").font(.sys(size: 11.5)).padding(9) } + .buttonStyle(.plain).foregroundStyle(.secondary).help("Copy") + } + } +} + +// MARK: - Structured content + +@MainActor struct HealthReportCard: View { + @Environment(AppModel.self) private var model + let report: HealthReportPayload + let bot: DatabaseBot + @State private var showDetails = false + + var body: some View { + let notable = report.findings.filter { $0.severity >= .warn } + let band = model.settings.bands.band(for: report.score) + VStack(alignment: .leading, spacing: 12) { + Text("🐘 " + title).font(Typo.bodyEmphasis) + Text(report.headline) + + HStack(alignment: .firstTextBaseline, spacing: 10) { + if report.score.completeness == .unavailable { + Text("—").font(.sys(size: 34, weight: .semibold)) + Text("Health score unavailable").font(.sys(size: 14)).foregroundStyle(Palette.muted) + } else { + Text("\(report.score.value)/100") + .font(.sys(size: 34, weight: .semibold)).kerning(-0.5) + .foregroundStyle(band.color) + Text("Health score").font(.sys(size: 14)).foregroundStyle(Palette.muted) + if let prev = report.previousScore, prev != report.score.value { + let d = report.score.value - prev + Text("\(d > 0 ? "+" : "")\(d) since last check").font(.sys(size: 13)).foregroundStyle(d > 0 ? Palette.healthy : .orange) + } + if report.score.completeness == .partial { + Text("Incomplete").font(.sys(size: 11, weight: .semibold)) + .padding(.horizontal, 6).padding(.vertical, 2) + .background(Color.orange.opacity(0.16), in: Capsule()).foregroundStyle(.orange) + .help(report.score.gaps.joined(separator: "\n")) + } + } + } + + Rectangle().fill(Palette.hairline).frame(height: 1) + + if showDetails { + ForEach(report.findings, id: \.key) { FindingCard(finding: $0, change: nil, bot: bot, standalone: false) } + } else { + ForEach(notable.prefix(5), id: \.key) { f in + Text("\(f.severity == .critical ? "🔴" : "🟠") \(f.isTentative ? "Possibly: " : "")\(f.title)") + } + if notable.count > 5 { Text("+\(notable.count - 5) more").foregroundStyle(Palette.muted) } + if notable.isEmpty && report.score.completeness != .unavailable { + Text("No warnings or critical findings.").foregroundStyle(Palette.muted) + } + } + if report.score.completeness != .complete && !report.score.gaps.isEmpty { + Text("Some statistics weren't visible: " + report.score.gaps.joined(separator: " · ")) + .font(.sys(size: 13)).foregroundStyle(Palette.muted) + } + + HStack(spacing: 8) { + if let top = notable.first, !bot.isDemo { + Button("Investigate") { model.send("Investigate: \(top.title). What's the evidence, and what should I do first?", to: bot.id) } + .buttonStyle(.pillProminent) + Button(showDetails ? "Hide details" : "Show details") { withAnimation(.snappy) { showDetails.toggle() } } + .buttonStyle(.pill) + } else { + Button(showDetails ? "Hide details" : "Show details") { withAnimation(.snappy) { showDetails.toggle() } } + .buttonStyle(.pillProminent) + } + Button("View metrics") { withAnimation(.snappy) { model.route = .metrics } }.buttonStyle(.pill) + } + .padding(.top, 2) + } + } + + private var title: String { + if report.isScheduled { return "Your daily database report" } + if report.isFirstRun == true { return "Your database is connected!" } + return "Health report" + } +} + +@MainActor struct FindingLine: View { + let finding: Finding + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: finding.severity.symbol).foregroundStyle(finding.severity.color).font(.sys(size: 13)) + Text((finding.isTentative ? "Possibly: " : "") + finding.title) + } + } +} + +/// A finding. Standalone (a proactive message) it fills the bubble like the +/// spec's "⚠️ Performance regression" card; nested in a report it is an inset card. +@MainActor struct FindingCard: View { + @Environment(AppModel.self) private var model + let finding: Finding + let change: FindingChange? + let bot: DatabaseBot + var standalone = false + @State private var expanded = false + + var body: some View { + let content = VStack(alignment: .leading, spacing: standalone ? 12 : 8) { + if standalone { + Text("\(finding.severity == .critical ? "🚨" : "⚠️") \(heading)").font(Typo.bodyEmphasis) + Text((finding.isTentative ? "Possibly: " : "") + finding.title) + } else { + Text("\(finding.severity == .critical ? "🔴" : (finding.severity == .warn ? "🟠" : "🔵")) \(finding.isTentative ? "Possibly: " : "")\(finding.title)") + .font(Typo.bodyEmphasis) + } + if !finding.detail.isEmpty { Text(finding.detail).foregroundStyle(Palette.muted).textSelection(.enabled) } + if let r = finding.remediation, !r.isEmpty { Text(r) } + if let est = finding.impact?.estimate, !est.isEmpty { + Text("Impact: \(est)").font(.sys(size: 13)).foregroundStyle(Palette.muted) + } + ForEach(finding.caveats ?? [], id: \.self) { c in + Text("⚠︎ " + c).font(.sys(size: 13)).foregroundStyle(.orange) + } + ForEach(finding.safety?.blockingCaveats ?? [], id: \.id) { g in + VStack(alignment: .leading, spacing: 2) { + Text("✋ Before \(g.action): \(g.text)").font(.sys(size: 13, weight: .medium)) + if let v = g.verify { Text("Verify first: \(v)").font(.sys(size: 13)).foregroundStyle(Palette.muted) } + } + .foregroundStyle(.red) + .padding(10).background(Color.red.opacity(0.08), in: RoundedRectangle(cornerRadius: 10)) + } + if let ev = finding.evidence, !ev.isEmpty { + DisclosureGroup(isExpanded: $expanded) { + VStack(alignment: .leading, spacing: 3) { + ForEach(Array(ev.prefix(30).enumerated()), id: \.offset) { _, e in + Text(e).font(.sys(size: 12, design: .monospaced)).textSelection(.enabled) + } + if ev.count > 30 { Text("+\(ev.count - 30) more").font(Typo.small).foregroundStyle(.secondary) } + } + .padding(.top, 4) + } label: { + Text("Evidence (\(ev.count))").font(Typo.small).foregroundStyle(.secondary) + } + } + HStack(spacing: 8) { + if !bot.isDemo { + Button("Investigate") { model.send("Explain the finding “\(finding.title)”: why it matters here and what to do.", to: bot.id) } + .buttonStyle(standalone ? .pillProminent : PillButtonStyle(prominent: true, compact: true)) + } + if finding.impact?.dimension == "latency" || finding.id.contains("quer") { + Button("View affected queries") { withAnimation(.snappy) { model.route = .metrics } } + .buttonStyle(standalone ? .pill : .pillSmall) + } + Button("Ignore") { model.mutate(bot.id) { $0.schedule.ignoredFindingKeys.insert(finding.key) } } + .buttonStyle(standalone ? .pill : .pillSmall) + .help("Hide this finding for this database in the app (does not change the engine's ignore rules)") + } + .padding(.top, 2) + } + if standalone { content } else { content.insetCard(padding: 14) } + } + + private var heading: String { + switch change { + case .escalated: return "Escalated to \(finding.severity.label.lowercased())" + case .deescalated: return "Improved" + case .resolved: return "Resolved" + default: + if finding.severity == .critical { return "Critical finding" } + if finding.impact?.dimension == "latency" || finding.id.contains("regress") { return "Performance regression" } + return "New warning" + } + } +} + +@MainActor struct TableCard: View { + let title: String + let columns: [String] + let rows: [[String]] + var framed = true + var body: some View { + let content = VStack(alignment: .leading, spacing: 10) { + HStack { + Text(title).font(Typo.bodyEmphasis) + Spacer() + Button { Pasteboard.copy(([columns] + rows).map { $0.joined(separator: "\t") }.joined(separator: "\n")) } label: { + Image(systemName: "doc.on.doc").font(.sys(size: 11.5)) + }.buttonStyle(.plain).foregroundStyle(.secondary).help("Copy as TSV") + } + ScrollView(.horizontal) { + Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 7) { + GridRow { ForEach(columns, id: \.self) { Text($0).font(Typo.micro.weight(.semibold)).foregroundStyle(.secondary) } } + ForEach(Array(rows.enumerated()), id: \.offset) { _, row in + GridRow { + ForEach(Array(row.enumerated()), id: \.offset) { i, cell in + Text(cell) + .font(i == row.count - 1 && cell.count > 30 ? .sys(size: 12, design: .monospaced) : .sys(size: 13).monospacedDigit()) + .lineLimit(2).textSelection(.enabled) + .frame(maxWidth: i == row.count - 1 ? 420 : nil, alignment: .leading) + } + } + } + } + } + } + if framed { content.card(padding: 14) } else { content } + } +} + +@MainActor struct MiniChart: View { + let metric: MetricKey + let points: [MetricPoint] + var body: some View { + VStack(alignment: .leading) { + Text(metric.label).font(Typo.bodyEmphasis) + Chart(points, id: \.at) { + AreaMark(x: .value("Time", $0.at), y: .value(metric.label, $0.value)).opacity(0.2) + LineMark(x: .value("Time", $0.at), y: .value(metric.label, $0.value)) + } + .frame(height: 120) + } + } +} + +@MainActor struct ErrorContent: View { + @Environment(AppModel.self) private var model + let title: String, detail: String, hint: String? + let message: ChatMessage + @State private var showDetail = false + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Label(title, systemImage: "exclamationmark.triangle.fill").font(Typo.bodyEmphasis).foregroundStyle(.orange) + if let hint { Text(hint) } + if !detail.isEmpty { + DisclosureGroup(isExpanded: $showDetail) { + Text(detail).font(.sys(size: 12, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) + } label: { Text("Details").font(Typo.small).foregroundStyle(.secondary) } + } + HStack(spacing: 8) { + if message.inReplyTo != nil { Button("Retry") { model.regenerate(message) } } + else { Button("Inspect again") { Task { await model.inspect(message.botID, reason: .manual) } } } + if title.contains("AI") || title.contains("credentials") || title.contains("permissions") { + Button("Open Settings") { openAppSettings() } + } + } + .buttonStyle(.pill) + } + } +} diff --git a/desktop/macos/Sources/PGBot/Components/PSQLViews.swift b/desktop/macos/Sources/PGBot/Components/PSQLViews.swift new file mode 100644 index 0000000..48824dc --- /dev/null +++ b/desktop/macos/Sources/PGBot/Components/PSQLViews.swift @@ -0,0 +1,258 @@ +import PGBotKit +import SwiftUI + +private let mono = { (size: CGFloat, weight: Font.Weight) in Font.sys(size: size, weight: weight, design: .monospaced) } + +/// What the user typed in PSQL mode, shown like a terminal line. +@MainActor struct PSQLInputBubble: View { + let input: String + let database: String + var body: some View { + let lines = input.components(separatedBy: "\n") + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(lines.enumerated()), id: \.offset) { i, line in + HStack(alignment: .firstTextBaseline, spacing: 6) { + Text(i == 0 ? "\(database)=>" : String(repeating: " ", count: database.count) + "->") + .foregroundStyle(Palette.healthy) + Text(line).foregroundStyle(Palette.userText) + } + } + } + .font(mono(13.5, .regular)) + .textSelection(.enabled) + .padding(.horizontal, 14).padding(.vertical, 10) + .background(Palette.userBubble, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) + } +} + +/// Results of one PSQL exchange: tables (or expanded records), command tags, +/// and psql-style errors. +@MainActor struct PSQLResultView: View { + let payload: PSQLResultPayload + + var body: some View { + let out = payload.output + VStack(alignment: .leading, spacing: 12) { + if let t = payload.title { Text(t).font(Typo.bodyEmphasis) } + if let missing = missingRelation { + Text("Did not find any relation named “\(missing)”.").font(mono(13, .regular)).foregroundStyle(.secondary) + } else { + ForEach(Array(out.results.enumerated()), id: \.offset) { i, r in + if r.columns.isEmpty { + Text(r.command.isEmpty ? "OK" : r.command).font(mono(13, .regular)).foregroundStyle(.secondary) + } else { + VStack(alignment: .leading, spacing: 6) { + if out.results.count > 1 && payload.title != nil, let sub = subtitle(i) { + Text(sub).font(Typo.small).foregroundStyle(.secondary) + } + if payload.expanded { PSQLRecords(result: r) } else { PSQLTable(result: r) } + PSQLFooter(result: r) + } + } + } + } + if let e = out.error { PSQLErrorView(error: e) } + if out.results.isEmpty && out.error == nil { Text("(no output)").font(mono(13, .regular)).foregroundStyle(.secondary) } + HStack(spacing: 6) { + Image(systemName: "lock.fill").font(.system(size: 9)) + Text("read-only · rolled back" + (out.elapsedMS > 0 ? " · \(Self.ms(out.elapsedMS))" : "")) + } + .font(Typo.micro).foregroundStyle(.tertiary) + } + } + + /// `\d name` that matched nothing returns empty column and index lists. + private var missingRelation: String? { + guard let t = payload.title, t.hasPrefix("Table "), payload.output.error == nil, + payload.output.results.first?.rows.isEmpty ?? false else { return nil } + return String(t.dropFirst(6)) + } + + private func subtitle(_ i: Int) -> String? { + guard payload.title?.hasPrefix("Table ") == true else { return nil } + return i == 0 ? "Columns" : "Indexes" + } + + static func ms(_ v: Double) -> String { v < 1 ? String(format: "%.2f ms", v) : (v < 1000 ? String(format: "%.0f ms", v) : String(format: "%.2f s", v / 1000)) } +} + +@MainActor struct PSQLTable: View { + let result: SQLRunResult + @State private var showAll = false + private let preview = 100 + + var body: some View { + let rows = showAll ? result.rows : Array(result.rows.prefix(preview)) + VStack(alignment: .leading, spacing: 6) { + ScrollView(.horizontal, showsIndicators: true) { + Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) { + GridRow { + ForEach(Array(result.columns.enumerated()), id: \.offset) { _, c in + VStack(alignment: c.isNumeric ? .trailing : .leading, spacing: 1) { + Text(c.name).font(mono(12.5, .semibold)) + Text(c.type).font(.sys(size: 10)).foregroundStyle(.tertiary) + } + .padding(.horizontal, 12).padding(.top, 8).padding(.bottom, 7) + .gridColumnAlignment(c.isNumeric ? .trailing : .leading) + } + } + // Views outside a GridRow span every column: full-width rules, psql-like. + Rectangle().fill(Palette.strongHairline).frame(height: 1) + ForEach(Array(rows.enumerated()), id: \.offset) { ri, row in + GridRow { + ForEach(Array(result.columns.enumerated()), id: \.offset) { ci, c in + PSQLCell(value: ci < row.count ? row[ci] : nil, numeric: c.isNumeric) + } + } + if ri < rows.count - 1 { Rectangle().fill(Palette.hairline).frame(height: 1) } + } + } + .fixedSize(horizontal: true, vertical: false) + } + .background(Palette.inset, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Palette.hairline)) + if result.rows.count > preview { + Button(showAll ? "Show first \(preview) rows" : "Show all \(result.rows.count) rows") { withAnimation(.snappy) { showAll.toggle() } } + .buttonStyle(.pillSmall) + } + } + } +} + +@MainActor struct PSQLCell: View { + let value: String? + let numeric: Bool + var body: some View { + Group { + if let v = value { + Text(v.count > 160 ? String(v.prefix(159)) + "…" : v.replacingOccurrences(of: "\n", with: "↵")) + .help(v.count > 40 ? v : "") + } else { + Text("null").italic().foregroundStyle(.tertiary) + } + } + .font(mono(12.5, .regular)) + .lineLimit(1) + .textSelection(.enabled) + .frame(maxWidth: 420, alignment: numeric ? .trailing : .leading) + .padding(.horizontal, 12).padding(.vertical, 6) + } +} + +/// `\x` expanded display: one block per record. +@MainActor struct PSQLRecords: View { + let result: SQLRunResult + var body: some View { + VStack(alignment: .leading, spacing: 10) { + ForEach(Array(result.rows.prefix(50).enumerated()), id: \.offset) { i, row in + VStack(alignment: .leading, spacing: 4) { + Text("─[ RECORD \(i + 1) ]─").font(mono(11.5, .semibold)).foregroundStyle(.secondary) + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 3) { + ForEach(Array(result.columns.enumerated()), id: \.offset) { ci, c in + GridRow { + Text(c.name).font(mono(12.5, .semibold)).foregroundStyle(.secondary) + if let v = ci < row.count ? row[ci] : nil { + Text(v).font(mono(12.5, .regular)).textSelection(.enabled) + } else { + Text("null").font(mono(12.5, .regular)).italic().foregroundStyle(.tertiary) + } + } + } + } + } + .padding(12) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Palette.inset, in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + if result.rows.count > 50 { Text("Showing 50 of \(result.rows.count) records.").font(Typo.small).foregroundStyle(.secondary) } + } + } +} + +@MainActor struct PSQLFooter: View { + let result: SQLRunResult + var body: some View { + HStack(spacing: 8) { + Text(rowsLabel).font(mono(12, .regular)).foregroundStyle(.secondary) + Text(PSQLResultView.ms(result.elapsedMS)).font(Typo.micro).foregroundStyle(.tertiary) + Spacer() + Menu { + Button("Copy as TSV") { Pasteboard.copy(PSQLExport.tsv(result)) } + Button("Copy as CSV") { Pasteboard.copy(PSQLExport.csv(result)) } + Button("Copy as Markdown") { Pasteboard.copy(PSQLExport.markdown(result)) } + } label: { + Label("Copy", systemImage: "doc.on.doc").font(Typo.small) + } + .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize() + .foregroundStyle(.secondary) + } + } + + private var rowsLabel: String { + let n = result.rowCount + return result.truncated ? "(first \(n) rows — more were not fetched)" : "(\(n) row\(n == 1 ? "" : "s"))" + } +} + +@MainActor struct PSQLErrorView: View { + let error: SQLRunError + var body: some View { + VStack(alignment: .leading, spacing: 5) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(error.isRefusal ? "BLOCKED" : "ERROR").font(mono(12.5, .bold)).foregroundStyle(error.isRefusal ? .orange : .red) + Text(error.message).font(mono(12.5, .regular)).textSelection(.enabled) + } + if let caret = caretLines { + VStack(alignment: .leading, spacing: 0) { + Text(caret.0) + Text(caret.1).foregroundStyle(.red) + } + .font(mono(12.5, .regular)) + } + if let d = error.detail, !d.isEmpty { line("DETAIL", d) } + if let h = error.hint, !h.isEmpty { line("HINT", h) } + if let code = error.sqlstate, !error.isRefusal { Text("SQLSTATE \(code)").font(Typo.micro).foregroundStyle(.tertiary) } + } + .padding(12) + .frame(maxWidth: .infinity, alignment: .leading) + .background((error.isRefusal ? Color.orange : Color.red).opacity(0.08), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + } + + private func line(_ label: String, _ text: String) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(label).font(mono(12, .semibold)).foregroundStyle(.secondary) + Text(text).font(mono(12, .regular)).foregroundStyle(.secondary).textSelection(.enabled) + } + } + + /// The statement line containing the error position, and a caret under it. + private var caretLines: (String, String)? { + guard let stmt = error.statement, let pos = error.position, pos > 0, pos <= stmt.count + 1 else { return nil } + let chars = Array(stmt) + let idx = min(pos - 1, chars.count - 1) + var start = idx; while start > 0 && chars[start - 1] != "\n" { start -= 1 } + var end = idx; while end < chars.count && chars[end] != "\n" { end += 1 } + let lineText = String(chars[start.. String { + ([r.columns.map(\.name)] + r.rows.map { $0.map { $0 ?? "" } }).map { $0.joined(separator: "\t") }.joined(separator: "\n") + } + static func csv(_ r: SQLRunResult) -> String { + func q(_ s: String?) -> String { + guard let s else { return "" } + return s.contains(where: { $0 == "," || $0 == "\"" || $0 == "\n" }) ? "\"" + s.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : s + } + return ([r.columns.map(\.name)] + r.rows.map { $0 }).map { $0.map(q).joined(separator: ",") }.joined(separator: "\n") + } + static func markdown(_ r: SQLRunResult) -> String { + func cell(_ s: String?) -> String { (s ?? "NULL").replacingOccurrences(of: "|", with: "\\|").replacingOccurrences(of: "\n", with: " ") } + let head = "| " + r.columns.map(\.name).joined(separator: " | ") + " |" + let rule = "|" + r.columns.map { $0.isNumeric ? " ---: " : " --- " }.joined(separator: "|") + "|" + return ([head, rule] + r.rows.map { "| " + $0.map(cell).joined(separator: " | ") + " |" }).joined(separator: "\n") + } +} diff --git a/desktop/macos/Sources/PGBot/DesignSystem/DesignSystem.swift b/desktop/macos/Sources/PGBot/DesignSystem/DesignSystem.swift new file mode 100644 index 0000000..719ce5c --- /dev/null +++ b/desktop/macos/Sources/PGBot/DesignSystem/DesignSystem.swift @@ -0,0 +1,373 @@ +import AppKit +import PGBotKit +import SwiftUI + +// MARK: - Color tokens +// +// A quiet, two-surface palette: a white canvas for the conversation and a soft +// gray sidebar. Color is reserved for the bots themselves and for severity. + +extension Color { + /// A color that resolves per appearance. + init(light: NSColor, dark: NSColor) { + self.init(nsColor: NSColor(name: nil) { $0.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light }) + } +} + +/// sRGB hex → NSColor. +func hex(_ v: UInt32, _ alpha: CGFloat = 1) -> NSColor { + NSColor(srgbRed: CGFloat((v >> 16) & 0xff) / 255, green: CGFloat((v >> 8) & 0xff) / 255, blue: CGFloat(v & 0xff) / 255, alpha: alpha) +} + +/// Dark mode follows Grok: near-black, neutral (no blue tint), low-contrast +/// gray surfaces, light text on dark-gray user bubbles, white primary buttons. +enum Palette { + static let canvas = Color(light: .white, dark: hex(0x151515)) + static let sidebar = Color(light: hex(0xf6f6f5), dark: hex(0x0d0d0d)) + /// Bot message bubbles. + static let bubble = Color(light: hex(0xf1f1f0), dark: hex(0x1f1f1f)) + /// The user's own messages. + static let userBubble = Color(light: hex(0xe9e9e7), dark: hex(0x2c2c2c)) + static let userText = Color(light: hex(0x141414), dark: hex(0xececec)) + /// Pills, the input, round buttons. + static let floating = Color(light: hex(0xf3f3f2), dark: hex(0x1c1c1c)) + static let floatingHover = Color(light: hex(0xe9e9e7), dark: hex(0x262626)) + /// Round controls inside the input ("+"). + static let control = Color(light: hex(0xe6e6e4), dark: hex(0x262626)) + /// Primary buttons and the send button. + static let primaryFill = Color(light: hex(0x141414), dark: hex(0xf5f5f5)) + static let onPrimary = Color(light: .white, dark: hex(0x0d0d0d)) + static let selection = Color(light: hex(0xebebea), dark: hex(0x1f1f1f)) + static let hover = Color(light: hex(0xf0f0ef), dark: hex(0x171717)) + static let hairline = Color(light: NSColor(white: 0, alpha: 0.08), dark: NSColor(white: 1, alpha: 0.07)) + static let strongHairline = Color(light: NSColor(white: 0, alpha: 0.14), dark: NSColor(white: 1, alpha: 0.12)) + /// Lighter secondary text. + static let muted = Color(light: hex(0x5f5f5f), dark: hex(0xa8a8a8)) + static let link = Color(light: hex(0x2f6fdb), dark: hex(0x6aa5ff)) + static let healthy = Color(nsColor: hex(0x22c55e)) + static let card = Color.primary.opacity(0.04) + static let subtleFill = Color.primary.opacity(0.06) + /// Cards and code inside a message: set off from the bubble (or from the canvas when messages are plain). + static var inset: Color { + Theme.plainMessages ? bubble : Color(light: .white, dark: hex(0x171717)) + } +} + +extension BotColor { + var color: Color { + switch self { + case .blue: Color(nsColor: hex(0x3b6cf5)) + case .green: Color(nsColor: hex(0x22b45a)) + case .orange: Color(nsColor: hex(0xf26a1b)) + case .purple: Color(red: 0.56, green: 0.40, blue: 0.95) + case .pink: Color(red: 0.93, green: 0.33, blue: 0.62) + case .yellow: Color(red: 0.95, green: 0.72, blue: 0.10) + case .red: Color(red: 0.92, green: 0.30, blue: 0.30) + case .teal: Color(red: 0.30, green: 0.72, blue: 0.62) + case .gray: Color(red: 0.55, green: 0.57, blue: 0.61) + // The spec's neutral avatar; it carries a database icon instead of the elephant. + case .black: Color(light: hex(0x2a2a2a), dark: hex(0x242424)) + } + } +} + +extension Severity { + var color: Color { + switch self { case .critical: .red; case .warn: .orange; case .info: .secondary } + } + var symbol: String { + switch self { + case .critical: "exclamationmark.octagon.fill" + case .warn: "exclamationmark.triangle.fill" + case .info: "info.circle.fill" + } + } +} + +extension ConnectionStatus { + var color: Color { + switch self { + case .healthy: Palette.healthy + case .degraded: .orange + case .critical, .unreachable: .red + case .unknown, .paused, .connecting: .gray + } + } + var label: String { + switch self { + case .unknown: "Not inspected yet" + case .connecting: "Inspecting…" + case .healthy: "Healthy" + case .degraded: "Needs attention" + case .critical: "Critical" + case .unreachable: "Unreachable" + case .paused: "Monitoring paused" + } + } +} + +extension HealthBands.Band { + var color: Color { + switch self { case .green: Palette.healthy; case .yellow: .yellow; case .orange: .orange; case .red: .red; case .gray: .secondary } + } +} + +// MARK: - Typography +// +// macOS's default body (13pt) is too small for a reading-first chat; messages +// use 15pt, like modern assistant apps. + +enum Typo { + static var body: Font { .sys(size: 15) } + static var bodyEmphasis: Font { .sys(size: 15, weight: .semibold) } + static var title: Font { .sys(size: 17, weight: .semibold) } + static var small: Font { .sys(size: 13) } + static var smallEmphasis: Font { .sys(size: 13, weight: .medium) } + static var micro: Font { .sys(size: 11.5) } +} + +/// User-chosen accent and text size (Settings → Appearance). Changing either +/// rebuilds the main window (RootView is keyed on them), so plain globals suffice. +enum Theme { + nonisolated(unsafe) static var textScale: CGFloat = 1 + nonisolated(unsafe) static var accent: Color = .accentColor + nonisolated(unsafe) static var plainMessages = false + nonisolated(unsafe) static var avatarStyle: AvatarStyle = .emoji + nonisolated(unsafe) static var animateAvatars = true + static func apply(_ s: AppSettings) { + animateAvatars = s.animateAvatars + avatarStyle = s.avatarStyle + textScale = s.textSize.scale + accent = s.accent.color + plainMessages = s.bubbleStyle == .plain + } +} + +extension Font { + /// A fixed point size that follows the app's text-size setting. + static func sys(size: CGFloat, weight: Font.Weight = .regular, design: Font.Design = .default) -> Font { + .system(size: size * Theme.textScale, weight: weight, design: design) + } +} + +// MARK: - Spacing & shape + +enum Space { + static let xs: CGFloat = 4, s: CGFloat = 8, m: CGFloat = 12, l: CGFloat = 16, xl: CGFloat = 24, xxl: CGFloat = 36 +} + +enum Radius { + static let card: CGFloat = 16, bubble: CGFloat = 22, composer: CGFloat = 26, chip: CGFloat = 8 +} + +/// The conversation column's readable width. +let readableWidth: CGFloat = 800 + +// MARK: - Modifiers + +struct CardStyle: ViewModifier { + var padding: CGFloat = Space.l + func body(content: Content) -> some View { + content.padding(padding) + .background(Palette.card, in: RoundedRectangle(cornerRadius: Radius.card, style: .continuous)) + } +} + +/// A white card that sits inside a gray message bubble. +struct InsetCardStyle: ViewModifier { + var padding: CGFloat = Space.m + func body(content: Content) -> some View { + content.padding(padding) + .background(Palette.inset, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + } +} + +/// Floating capsule chrome (title pill, header actions, status notes). +struct FloatingPill: ViewModifier { + var height: CGFloat = 34 + func body(content: Content) -> some View { + content.padding(.horizontal, 14).frame(height: height) + .background(Palette.floating, in: Capsule()) + .overlay(Capsule().strokeBorder(Palette.hairline)) + } +} + +/// Outline capsule (spec "Metrics" button): transparent, hairline border. +struct OutlinePill: ViewModifier { + var active = false + @State private var hovering = false + func body(content: Content) -> some View { + content.padding(.horizontal, 14).frame(height: 36) + .background(active || hovering ? Palette.floatingHover : .clear, in: Capsule()) + .overlay(Capsule().strokeBorder(Palette.strongHairline)) + .contentShape(Capsule()) + .onHover { hovering = $0 } + } +} + +extension View { + func card(padding: CGFloat = Space.l) -> some View { modifier(CardStyle(padding: padding)) } + func insetCard(padding: CGFloat = Space.m) -> some View { modifier(InsetCardStyle(padding: padding)) } + func floatingPill(height: CGFloat = 34) -> some View { modifier(FloatingPill(height: height)) } + func outlinePill(active: Bool = false) -> some View { modifier(OutlinePill(active: active)) } + func hoverHighlight(cornerRadius: CGFloat = 8) -> some View { modifier(HoverHighlight(cornerRadius: cornerRadius)) } +} + +struct HoverHighlight: ViewModifier { + var cornerRadius: CGFloat = 8 + @State private var hovering = false + func body(content: Content) -> some View { + content + .background(RoundedRectangle(cornerRadius: cornerRadius, style: .continuous).fill(hovering ? Palette.subtleFill : .clear)) + .onHover { hovering = $0 } + } +} + +/// Message buttons (spec): 36pt capsules. Primary is #f0f0ec with dark text; +/// secondary is an outline that fills on hover. +struct PillButtonStyle: ButtonStyle { + var prominent = false + var compact = false + func makeBody(configuration: Configuration) -> some View { + PillBody(configuration: configuration, prominent: prominent, compact: compact) + } + + private struct PillBody: View { + let configuration: ButtonStyleConfiguration + let prominent: Bool + let compact: Bool + @State private var hovering = false + @Environment(\.isEnabled) private var enabled + var body: some View { + configuration.label + .font(.sys(size: compact ? 13 : 14, weight: .medium)) + .padding(.horizontal, compact ? 12 : 16) + .frame(height: compact ? 30 : 36) + .foregroundStyle(prominent ? Palette.onPrimary : Color.primary) + .background(prominent ? Palette.primaryFill : (hovering ? Palette.floatingHover : Color.clear), in: Capsule()) + .overlay(Capsule().strokeBorder(prominent ? Color.clear : Palette.strongHairline)) + .opacity(configuration.isPressed ? 0.75 : (enabled ? 1 : 0.45)) + .contentShape(Capsule()) + .onHover { hovering = $0 } + } + } +} + +extension ButtonStyle where Self == PillButtonStyle { + static var pill: PillButtonStyle { PillButtonStyle() } + static var pillProminent: PillButtonStyle { PillButtonStyle(prominent: true) } + static var pillSmall: PillButtonStyle { PillButtonStyle(compact: true) } +} + +// MARK: - Controls + +/// A white round icon button, as in the sidebar's top corner. +@MainActor struct CircleButton: View { + let symbol: String + let help: String + var size: CGFloat = 34 + var badge = false + let action: () -> Void + var body: some View { + Button(action: action) { CircleIcon(symbol: symbol, size: size, badge: badge) } + .buttonStyle(.plain) + .help(help) + .accessibilityLabel(help) + } +} + +@MainActor struct CircleIcon: View { + let symbol: String + var size: CGFloat = 34 + var badge = false + var outlined = false + @State private var hovering = false + var body: some View { + Image(systemName: symbol) + .font(.system(size: size * 0.41, weight: .medium)) + .foregroundStyle(.primary.opacity(0.85)) + .frame(width: size, height: size) + .background(outlined ? (hovering ? Palette.floatingHover : .clear) : (hovering ? Palette.floatingHover : Palette.floating), in: Circle()) + .overlay(Circle().strokeBorder(outlined ? Palette.strongHairline : .clear)) + .overlay(alignment: .topTrailing) { + if badge { + Circle().fill(Theme.accent).frame(width: 9, height: 9) + .overlay(Circle().strokeBorder(Palette.canvas, lineWidth: 2)) + .offset(x: 1, y: -1) + } + } + .contentShape(Circle()) + .onHover { hovering = $0 } + } +} + +/// A borderless icon button (used in dense places like tables and toolbars). +@MainActor struct IconButton: View { + let symbol: String + let help: String + var size: CGFloat = 15 + var badge: Int = 0 + let action: () -> Void + var body: some View { + Button(action: action) { + Image(systemName: symbol).font(.sys(size: size)).frame(width: 30, height: 28).contentShape(Rectangle()) + .overlay(alignment: .topTrailing) { + if badge > 0 { Circle().fill(Theme.accent).frame(width: 7, height: 7).offset(x: -5, y: 5) } + } + } + .buttonStyle(.plain).foregroundStyle(.secondary).hoverHighlight().help(help).accessibilityLabel(help) + } +} + +@MainActor struct DemoBadge: View { + var body: some View { + Text("DEMO") + .font(.sys(size: 9, weight: .bold, design: .rounded)) + .padding(.horizontal, 5).padding(.vertical, 1.5) + .background(Color.purple.opacity(0.14), in: Capsule()) + .foregroundStyle(.purple) + .accessibilityLabel("Demo data") + } +} + +@MainActor struct StatusDot: View { + let status: ConnectionStatus + var size: CGFloat = 8 + var body: some View { + Circle().fill(status.color).frame(width: size, height: size) + .overlay(Circle().strokeBorder(Palette.sidebar, lineWidth: size > 8 ? 2 : 0)) + .accessibilityLabel(status.label) + } +} + +/// Settings is a regular window scene ("settings"): on macOS 14 the Settings +/// scene can only be opened through SettingsLink, not from code, menus or the +/// menu bar. RootView hands us its OpenWindowAction at launch. +@MainActor enum WindowOpener { static var open: OpenWindowAction? } + +@MainActor func openAppSettings(tab: String? = nil) { + if let tab { UserDefaults.standard.set(tab, forKey: "settingsTab") } + NSApp.activate(ignoringOtherApps: true) + WindowOpener.open?(id: "settings") + // When PGBot isn't frontmost, SwiftUI can create the window without ordering + // it in; bring it forward explicitly. + for delay in [0.0, 0.15, 0.4, 0.9] { + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { + guard let w = NSApp.windows.first(where: { $0.title == "PGBot Settings" }) else { + WindowOpener.open?(id: "settings") // not created yet (or dropped): ask again + return + } + guard !w.isVisible || !w.isKeyWindow else { return } + NSApp.activate(ignoringOtherApps: true) + w.makeKeyAndOrderFront(nil) + } + } +} + +/// "Today 2:04 PM", "Yesterday 9:00 AM", "Mon, Nov 23 2:04 AM". +func conversationStamp(_ d: Date) -> String { + let cal = Calendar.current, time = d.formatted(date: .omitted, time: .shortened) + if cal.isDateInToday(d) { return "Today \(time)" } + if cal.isDateInYesterday(d) { return "Yesterday \(time)" } + return d.formatted(.dateTime.weekday(.abbreviated).month(.abbreviated).day()) + " " + time +} diff --git a/desktop/macos/Sources/PGBot/Features/Authentication/SignInView.swift b/desktop/macos/Sources/PGBot/Features/Authentication/SignInView.swift new file mode 100644 index 0000000..b9fda5e --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Authentication/SignInView.swift @@ -0,0 +1,123 @@ +import AuthenticationServices +import PGBotKit +import SwiftUI + +/// Runs the browser leg of OAuth in the user's system browser session. +protocol WebAuthenticator { + @MainActor func authenticate(url: URL, callbackScheme: String) async throws -> URL +} + +final class SystemBrowserAuthenticator: NSObject, WebAuthenticator, ASWebAuthenticationPresentationContextProviding { + private var session: ASWebAuthenticationSession? + + @MainActor func authenticate(url: URL, callbackScheme: String) async throws -> URL { + try await withCheckedThrowingContinuation { cont in + let s = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) { callback, error in + if let callback { cont.resume(returning: callback); return } + if let e = error as? ASWebAuthenticationSessionError, e.code == .canceledLogin { cont.resume(throwing: AuthError.cancelled); return } + cont.resume(throwing: AuthError.network(error?.localizedDescription ?? "unknown")) + } + s.presentationContextProvider = self + // Share cookies with the user's browser so existing Google/GitHub sessions work. + s.prefersEphemeralWebBrowserSession = false + session = s + if !s.start() { cont.resume(throwing: AuthError.network("Couldn't open the browser")) } + } + } + + func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + MainActor.assumeIsolated { NSApp.keyWindow ?? NSApp.windows.first ?? ASPresentationAnchor() } + } +} + +@MainActor struct SignInView: View { + @Environment(AppModel.self) private var model + @State private var authenticator = SystemBrowserAuthenticator() + + var body: some View { + VStack(spacing: 0) { + Spacer() + VStack(spacing: Space.l) { + PGBotLogo(size: 84) + Text("PGBot").font(.sys(size: 34, weight: .semibold, design: .rounded)) + Text("An AI agent for every Postgres database.") + .font(.title2.weight(.medium)) + .multilineTextAlignment(.center) + Text("Connect your databases. Understand what's happening. Know what to fix.") + .font(.title3).foregroundStyle(.secondary).multilineTextAlignment(.center) + } + .padding(.bottom, Space.xxl) + + VStack(spacing: Space.m) { + providerButton(.google, title: "Continue with Google", symbol: "g.circle.fill") + providerButton(.github, title: "Continue with GitHub", symbol: "chevron.left.forwardslash.chevron.right") + if !model.authService.config.isConfigured { + VStack(spacing: Space.s) { + Text("Account sign-in isn't configured in this build.") + .font(.callout).foregroundStyle(.secondary) + Button("Continue without an account") { Task { await model.continueLocally() } } + .buttonStyle(.link) + Text("Everything runs locally. Your databases and history stay on this Mac.") + .font(.caption).foregroundStyle(.tertiary).multilineTextAlignment(.center) + } + .padding(.top, Space.s) + } + } + .frame(width: 320) + + if case .signedOut(let error?) = model.auth { + Label(error, systemImage: "exclamationmark.triangle.fill") + .font(.callout).foregroundStyle(.orange) + .padding(.top, Space.l).frame(maxWidth: 420) + } + Spacer() + HStack(spacing: Space.l) { + Link("Terms of Service", destination: URL(string: "https://pgbot.dev/terms")!) + Text("·").foregroundStyle(.tertiary) + Link("Privacy Policy", destination: URL(string: "https://pgbot.dev/privacy")!) + } + .font(.footnote).foregroundStyle(.secondary) + .padding(.bottom, Space.xl) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(.background) + } + + private func providerButton(_ p: AuthProvider, title: String, symbol: String) -> some View { + let busy = model.auth == .signingIn(p) + return Button { + Task { await model.signIn(with: p, using: authenticator) } + } label: { + HStack(spacing: Space.s) { + if busy { ProgressView().controlSize(.small) } else { Image(systemName: symbol) } + Text(busy ? "Waiting for your browser…" : title).fontWeight(.medium) + } + .frame(maxWidth: .infinity).frame(height: 40) + } + .buttonStyle(.plain) + .background(Palette.subtleFill, in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(Palette.hairline)) + .disabled(!model.authService.config.isConfigured || model.auth == .signingIn(.google) || model.auth == .signingIn(.github)) + .opacity(model.authService.config.isConfigured ? 1 : 0.45) + } +} + +@MainActor struct RootView: View { + @Environment(AppModel.self) private var model + @Environment(\.openWindow) private var openWindow + var body: some View { + Group { + switch model.auth { + case .restoring: + VStack(spacing: Space.l) { PGBotLogo(size: 64); ProgressView().controlSize(.small) } + .frame(maxWidth: .infinity, maxHeight: .infinity) + case .signedOut, .signingIn: + SignInView() + case .signedIn: + MainView() + } + } + .frame(minWidth: 860, minHeight: 560) + .onAppear { WindowOpener.open = openWindow } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Chat/BotDetailView.swift b/desktop/macos/Sources/PGBot/Features/Chat/BotDetailView.swift new file mode 100644 index 0000000..eb4c033 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Chat/BotDetailView.swift @@ -0,0 +1,141 @@ +import PGBotKit +import SwiftUI + +/// No header bar: content runs edge to edge and the bot's name floats on top +/// in a pill, with a couple of quiet actions on the right. +@MainActor struct BotDetailView: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + + var body: some View { + VStack(spacing: 0) { + BotHeader(bot: bot) + StatusNotes() + Group { + switch model.route { + case .chat: ConversationView(bot: bot) + case .metrics: MetricsView(bot: bot) + case .logs: LogsView(bot: bot) + } + } + .frame(maxHeight: .infinity) + } + .navigationTitle(bot.displayName) + } +} + +/// 62pt header: the bot in a centered pill, quiet outline actions on the right. +@MainActor struct BotHeader: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + @State private var showingInfo = false + @State private var showingNotifications = false + + var body: some View { + ZStack { + Button { showingInfo.toggle() } label: { + HStack(spacing: 8) { + BotAvatarView(bot: bot, size: 22) + Text(bot.displayName).font(.sys(size: 15, weight: .medium)) + StatusDot(status: model.inspecting.contains(bot.id) ? .connecting : bot.status, size: 7) + if model.isPSQL(bot.id) { + Text("PSQL").font(.sys(size: 10, weight: .bold, design: .monospaced)) + .padding(.horizontal, 5).padding(.vertical, 1.5) + .background(Palette.healthy.opacity(0.16), in: Capsule()).foregroundStyle(Palette.healthy) + } + if bot.isDemo { DemoBadge() } + } + .padding(.leading, 8).padding(.trailing, 14).padding(.vertical, 6) + .background(Palette.floating, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + .contentShape(RoundedRectangle(cornerRadius: 20)) + } + .buttonStyle(.plain) + .popover(isPresented: $showingInfo, arrowEdge: .bottom) { DatabaseInfoPopover(bot: bot) } + .accessibilityLabel("\(bot.displayName), \(bot.status.label). Show database details") + + HStack(spacing: 8) { + if model.route != .chat { + Button { withAnimation(.snappy) { model.route = .chat } } label: { + Label("Chat", systemImage: "chevron.left").font(.sys(size: 14, weight: .medium)).outlinePill() + } + .buttonStyle(.plain) + .keyboardShortcut(.escape, modifiers: []) + } + Spacer() + Button { withAnimation(.snappy) { model.route = model.route == .metrics ? .chat : .metrics } } label: { + Text("Metrics").font(.sys(size: 14, weight: .medium)).outlinePill(active: model.route == .metrics) + } + .buttonStyle(.plain) + .help(model.route == .metrics ? "Back to chat" : "Metrics") + Button { withAnimation(.snappy) { model.route = model.route == .logs ? .chat : .logs } } label: { + CircleIcon(symbol: "doc.plaintext", size: 36, outlined: true) + } + .buttonStyle(.plain).help("Logs") + Button { showingNotifications.toggle() } label: { + CircleIcon(symbol: "bell", size: 36, badge: model.notifications.contains { $0.botID == bot.id && !$0.read }, outlined: true) + } + .buttonStyle(.plain).help("Notifications") + .popover(isPresented: $showingNotifications, arrowEdge: .bottom) { NotificationCenterView(initialBot: bot.id) } + Menu { + Button("Run Inspection") { Task { await model.inspect(bot.id, reason: .manual) } } + .disabled(model.inspecting.contains(bot.id)) + Button("Database Settings…") { model.settingsForBot = bot } + Divider() + Button(bot.muted ? "Unmute Notifications" : "Mute Notifications") { model.mutate(bot.id) { $0.muted.toggle() } } + Button(bot.schedule.enabled ? "Pause Monitoring" : "Resume Monitoring") { model.mutate(bot.id) { $0.schedule.enabled.toggle() } } + Divider() + Button("Export Conversation…") { model.exportConversation(bot.id) } + Button("Export Inspection Report…") { model.exportInspection(bot.id) }.disabled(model.latest[bot.id] == nil) + if model.demoMode { Divider(); Button("Exit Demo Mode") { model.setDemoMode(false) } } + } label: { + CircleIcon(symbol: "ellipsis", size: 36, outlined: true) + } + .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize() + .help("More") + } + } + .padding(.horizontal, 14) + .frame(height: 62) + } +} + +/// Facts about the connection — never the password or the full connection string. +@MainActor struct DatabaseInfoPopover: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + var body: some View { + let ctx = model.latest[bot.id]?.context + VStack(alignment: .leading, spacing: Space.m) { + HStack(spacing: Space.m) { + BotAvatarView(bot: bot, size: 40) + VStack(alignment: .leading) { + Text(bot.displayName).font(Typo.bodyEmphasis) + if !bot.description.isEmpty { Text(bot.description).font(Typo.small).foregroundStyle(.secondary) } + } + } + Grid(alignment: .leading, horizontalSpacing: Space.l, verticalSpacing: 6) { + row("PostgreSQL", ctx?.server.displayVersion ?? "Unknown until the first inspection") + row("Host", "\(bot.connection.host):\(bot.connection.port)") + row("Database", bot.connection.database) + row("User", bot.connection.username) + if let p = ctx?.server.provider, !p.isEmpty, p != "unknown" { row("Provider", p.uppercased()) } + row("Environment", bot.environment.label) + row("Status", model.inspecting.contains(bot.id) ? "Inspecting…" : bot.status.label) + row("Last inspection", bot.lastInspectedAt.map { $0.formatted(.relative(presentation: .named)) } ?? "Never") + row("Monitoring", bot.isDemo ? "Demo data" : (!bot.schedule.enabled || model.monitoringPaused ? "Paused" + : "Every \(Duration.seconds(bot.schedule.intervalSeconds).formatted(.units(allowed: [.hours, .minutes], width: .wide))) while this Mac is awake")) + if let has = ctx?.server.hasPgMonitor { row("pg_monitor", has ? "Granted" : "Missing — some statistics hidden") } + } + .font(Typo.small) + } + .padding(Space.l) + .frame(width: 340) + } + + private func row(_ k: String, _ v: String) -> some View { + GridRow { + Text(k).foregroundStyle(.secondary) + Text(v).textSelection(.enabled) + } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift b/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift new file mode 100644 index 0000000..8716294 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift @@ -0,0 +1,273 @@ +import PGBotKit +import SwiftUI + +@MainActor struct ConversationView: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + @State private var search = "" + @State private var searching = false + @State private var atBottom = true + + var body: some View { + let all = model.messages(for: bot.id) + let shown = search.isEmpty ? all : all.filter { $0.plainText.localizedCaseInsensitiveContains(search) } + ZStack(alignment: .bottom) { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: model.settings.density == .compact ? 6 : 10) { + Color.clear.frame(height: searching ? 48 : 4) + if all.isEmpty { emptyState } + ForEach(Array(shown.enumerated()), id: \.element.id) { i, m in + if model.settings.showTimestamps && (i == 0 || m.createdAt.timeIntervalSince(shown[i - 1].createdAt) > 15 * 60) { + Text(conversationStamp(m.createdAt)) + .font(Typo.small).foregroundStyle(.secondary) + .frame(maxWidth: .infinity).padding(.vertical, 6) + } + MessageView(message: m, bot: bot).id(m.id) + } + if model.generating[bot.id] != nil || model.inspecting.contains(bot.id) { + ThinkingRow(bot: bot, label: model.inspecting.contains(bot.id) ? "Inspecting the database…" + : (model.isPSQL(bot.id) ? "Running…" : "Thinking…")) + } + Color.clear.frame(height: 110).id("bottom") + .onAppear { atBottom = true } + .onDisappear { atBottom = false } + } + .frame(maxWidth: readableWidth) + .padding(.horizontal, 22) + .frame(maxWidth: .infinity) + } + .scrollIndicators(.automatic) + .defaultScrollAnchor(.bottom) + .onChange(of: model.scrollTarget) { _, target in + guard let target else { return } + withAnimation(.snappy) { proxy.scrollTo(target, anchor: .center) } + } + .onChange(of: all.count) { _, _ in withAnimation(.snappy) { proxy.scrollTo("bottom", anchor: .bottom) } } + .onChange(of: model.generating[bot.id] != nil) { _, _ in withAnimation { proxy.scrollTo("bottom", anchor: .bottom) } } + .onAppear { proxy.scrollTo(model.scrollTarget ?? all.last?.id, anchor: .bottom) } + .overlay(alignment: .bottom) { + if !atBottom { + Button { withAnimation(.snappy) { proxy.scrollTo("bottom", anchor: .bottom) } } label: { + CircleIcon(symbol: "arrow.down", size: 34) + } + .buttonStyle(.plain).help("Scroll to latest") + .padding(.bottom, 96) + .transition(.opacity.combined(with: .scale(scale: 0.9))) + } + } + .animation(.snappy(duration: 0.2), value: atBottom) + } + // Fade the conversation out under the composer. + LinearGradient(colors: [Palette.canvas.opacity(0), Palette.canvas], startPoint: .top, endPoint: .bottom) + .frame(height: 70).allowsHitTesting(false) + ChatComposer(bot: bot) + } + .overlay(alignment: .top) { + if searching { + HStack(spacing: 8) { + Image(systemName: "magnifyingglass").foregroundStyle(.secondary) + TextField("Search this conversation", text: $search).textFieldStyle(.plain) + Text("\(shown.count) of \(all.count)").font(Typo.micro).foregroundStyle(.secondary) + Button { searching = false; search = "" } label: { Image(systemName: "xmark.circle.fill") } + .buttonStyle(.plain).foregroundStyle(.secondary) + } + .frame(width: 380) + .floatingPill(height: 34) + .padding(.top, 6) + } + } + .background { + Button("") { searching.toggle(); if !searching { search = "" } }.keyboardShortcut("f").hidden() + } + } + + private var emptyState: some View { + VStack(spacing: Space.m) { + BotAvatarView(bot: bot, size: 72) + Text(bot.displayName).font(.sys(size: 22, weight: .semibold)) + Text("Ask anything about this database, or pick an action from +.") + .font(Typo.body).foregroundStyle(.secondary) + Button("Run health check") { model.run(.healthCheck, on: bot.id) }.buttonStyle(.pill) + } + .frame(maxWidth: .infinity).padding(.top, 120) + } +} + +@MainActor struct ThinkingRow: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + let label: String + @State private var started = Date() + var body: some View { + HStack(spacing: 10) { + ProgressView().controlSize(.small) + TimelineView(.periodic(from: started, by: 1)) { ctx in + HStack(spacing: 6) { + Text(label) + Text("\(Int(ctx.date.timeIntervalSince(started)))s").monospacedDigit().foregroundStyle(.tertiary) + } + } + if model.generating[bot.id] != nil { + Button("Stop") { model.stopGenerating(bot.id) }.buttonStyle(.pill) + } + } + .font(Typo.body).foregroundStyle(.secondary) + .padding(.horizontal, 18).padding(.vertical, 12) + .background(Palette.bubble, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + } +} + +// MARK: - Composer + +@MainActor struct ChatComposer: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + @State private var text = "" + @State private var historyIndex: Int? + @FocusState private var focused: Bool + + var body: some View { + let psql = model.isPSQL(bot.id) + VStack(spacing: 8) { + if psql { psqlBar } + field(psql: psql) + } + .frame(maxWidth: readableWidth + 44) + .padding(.horizontal, 22).padding(.bottom, 18) + .onAppear { focused = true } + .onChange(of: psql) { _, _ in focused = true; historyIndex = nil } + } + + /// "PSQL · read-only" bar above the console input. + private var psqlBar: some View { + HStack(spacing: 10) { + Label("PSQL", systemImage: "terminal").font(.sys(size: 12, weight: .semibold, design: .monospaced)) + .foregroundStyle(Palette.healthy) + Text(verbatim: "read-only · end with ; · ↑↓ history · \\? help").font(Typo.micro).foregroundStyle(.secondary) + Spacer() + Button("Exit") { model.setPSQLMode(false, for: bot.id) }.buttonStyle(.pillSmall) + } + .padding(.horizontal, 10) + } + + private func field(psql: Bool) -> some View { + let busy = model.generating[bot.id] != nil + return HStack(alignment: .bottom, spacing: 10) { + Menu { + Button { model.setPSQLMode(!psql, for: bot.id) } label: { + Label(psql ? "Exit PSQL Mode" : "PSQL Mode", systemImage: "terminal") + } + Divider() + ForEach(QuickAction.allCases) { a in + Button { model.run(a, on: bot.id) } label: { Label(a.label, systemImage: a.symbol) } + } + Divider() + AIModelMenu() + } label: { + Image(systemName: "plus").font(.system(size: 16, weight: .medium)).foregroundStyle(.primary.opacity(0.85)) + .frame(width: 38, height: 38) + .background(Palette.control, in: Circle()) + .contentShape(Circle()) + } + .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize() + .help("Actions and model") + .accessibilityLabel("Actions") + + if psql { + Text("\(bot.connection.database)=>") + .font(.sys(size: 14, weight: .medium, design: .monospaced)) + .foregroundStyle(Palette.healthy) + .padding(.vertical, 9) + } + TextField(psql ? "SELECT … ; or \\dt" : "Ask your database…", text: $text, axis: .vertical) + .textFieldStyle(.plain) + .font(psql ? .sys(size: 14, design: .monospaced) : Typo.body) + .lineLimit(1...12) + .padding(.vertical, 9) + .focused($focused) + .onKeyPress(.return, phases: .down) { press in + if press.modifiers.contains(.shift) || press.modifiers.contains(.option) { text += "\n"; return .handled } + if press.modifiers.contains(.command) { submit(); return .handled } + // PSQL mode follows psql: Return runs a meta-command or a statement ending in ";". + if psql { if PSQL.isComplete(text) { submit() } else { text += "\n" }; return .handled } + if model.settings.sendWithReturn { submit(); return .handled } + text += "\n"; return .handled + } + .onKeyPress(.upArrow) { psql ? browseHistory(-1) : .ignored } + .onKeyPress(.downArrow) { psql ? browseHistory(1) : .ignored } + .onKeyPress(.escape) { if busy { model.stopGenerating(bot.id); return .handled }; return .ignored } + .accessibilityLabel("Message \(bot.displayName)") + + if busy { + Button { model.stopGenerating(bot.id) } label: { + Image(systemName: "stop.fill").font(.system(size: 12)).foregroundStyle(Palette.onPrimary) + .frame(width: 38, height: 38).background(Palette.primaryFill, in: Circle()) + } + .buttonStyle(.plain).help("Stop (Esc)").accessibilityLabel("Stop generating") + } else { + Button(action: submit) { + Image(systemName: psql ? "return" : "arrow.up").font(.system(size: 15, weight: .semibold)) + .foregroundStyle(Palette.onPrimary) + .frame(width: 38, height: 38) + .background(Palette.primaryFill, in: Circle()) + .opacity(canSend ? 1 : 0.35) + } + .buttonStyle(.plain).disabled(!canSend) + .help(psql ? "Run (Return after ; or ⌘Return)" : (model.settings.sendWithReturn ? "Send (Return)" : "Send (⌘Return)")).accessibilityLabel("Send") + } + } + .padding(8) + .frame(minHeight: 54) + .background(Palette.floating, in: RoundedRectangle(cornerRadius: 27, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 27, style: .continuous) + .strokeBorder(psql ? Palette.healthy.opacity(0.45) : Palette.hairline.opacity(1.25))) + } + + /// ↑/↓ walk the database's PSQL history when the input is a single line. + private func browseHistory(_ step: Int) -> KeyPress.Result { + let history = model.psqlHistory[bot.id] ?? [] + guard !history.isEmpty, !text.contains("\n") || historyIndex != nil else { return .ignored } + let current = historyIndex ?? history.count + let next = current + step + if next < 0 { return .handled } + if next >= history.count { historyIndex = nil; text = ""; return .handled } + historyIndex = next + text = history[next] + return .handled + } + + private var canSend: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + + private func submit() { + guard canSend, model.generating[bot.id] == nil else { return } + if model.isPSQL(bot.id) { model.runPSQL(text, on: bot.id) } else { model.send(text, to: bot.id) } + text = "" + historyIndex = nil + } +} + +/// The model choice lives in the + menu instead of cluttering the composer. +@MainActor struct AIModelMenu: View { + @Environment(AppModel.self) private var model + var body: some View { + Menu("Model: \(model.settings.ai.model.isEmpty ? model.settings.ai.provider.label : model.settings.ai.model)") { + ForEach(AIProviderKind.allCases) { p in + Menu(p.label) { + ForEach(p.suggestedModels.isEmpty ? ["Default"] : p.suggestedModels, id: \.self) { m in + Button { + model.settings.ai.provider = p + model.settings.ai.model = m == "Default" ? "" : m + } label: { + if model.settings.ai.provider == p && (model.settings.ai.model == m || (m == "Default" && model.settings.ai.model.isEmpty)) { + Label(m, systemImage: "checkmark") + } else { Text(m) } + } + } + } + } + Divider() + Button("AI Settings…") { openAppSettings(tab: "ai") } + } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Logs/LogsView.swift b/desktop/macos/Sources/PGBot/Features/Logs/LogsView.swift new file mode 100644 index 0000000..ccda933 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Logs/LogsView.swift @@ -0,0 +1,160 @@ +import PGBotKit +import SwiftUI + +@MainActor struct LogsView: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + + enum Level: String, CaseIterable, Identifiable { + case all = "All", error = "Errors", warn = "Warnings", info = "Info", query = "Queries" + var id: String { rawValue } + } + enum TimeWindow: String, CaseIterable, Identifiable { + case all = "Any time", hour = "Last hour", day = "Last 24 hours" + var id: String { rawValue } + var seconds: TimeInterval? { switch self { case .all: nil; case .hour: 3600; case .day: 86400 } } + } + + @State private var entries: [LogEntry] = [] + @State private var loading = false + @State private var error: EngineError? + @State private var level: Level = .all + @State private var window: TimeWindow = .all + @State private var search = "" + @State private var expanded: Set = [] + @State private var live = false + @State private var liveTask: Task? + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: Space.m) { + Picker("Level", selection: $level) { ForEach(Level.allCases) { Text($0.rawValue).tag($0) } } + .pickerStyle(.segmented).labelsHidden().frame(width: 340) + Picker("Time", selection: $window) { ForEach(TimeWindow.allCases) { Text($0.rawValue).tag($0) } } + .labelsHidden().frame(width: 130) + TextField("Search logs", text: $search).textFieldStyle(.roundedBorder).frame(maxWidth: 240) + Spacer() + Toggle(isOn: $live) { Label("Live", systemImage: "dot.radiowaves.left.and.right") } + .toggleStyle(.button).disabled(bot.isDemo) + .help("Refresh every 10 seconds while this view is open") + Button { Task { await load() } } label: { Image(systemName: "arrow.clockwise") }.disabled(loading).help("Refresh") + } + .padding(.horizontal, Space.xl).padding(.top, 4).padding(.bottom, Space.m) + content + } + .task { await load() } + .onChange(of: live) { _, on in + liveTask?.cancel() + guard on else { return } + liveTask = Task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(10)); await load() } } + } + .onDisappear { liveTask?.cancel() } + } + + @ViewBuilder private var content: some View { + if loading && entries.isEmpty { + ProgressView("Reading the server log…").frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let error, entries.isEmpty { + ContentUnavailableView { + Label("Logs aren't available", systemImage: "doc.questionmark") + } description: { + VStack(spacing: 6) { + Text(error.hint) + Text("PGBot reads the log over SQL (pg_read_binary_file), which needs one extra grant. Managed providers such as Supabase, Neon and RDS expose logs through their own APIs instead.") + .foregroundStyle(.secondary) + if !error.detail.isEmpty { Text(error.detail).font(.caption.monospaced()).foregroundStyle(.tertiary) } + } + } actions: { + Button("Try again") { Task { await load() } } + } + } else if filtered.isEmpty { + ContentUnavailableView("No matching log entries", systemImage: "line.3.horizontal.decrease.circle", + description: Text(entries.isEmpty ? "The server log is empty." : "Try a different filter.")) + } else { + List(filtered) { e in + LogRow(entry: e, expanded: expanded.contains(e.id)) { + if expanded.contains(e.id) { expanded.remove(e.id) } else { expanded.insert(e.id) } + } explain: { + model.explainLog(e, botID: bot.id) + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + } + } + + private var filtered: [LogEntry] { + entries.filter { e in + let lvl: Bool = switch level { + case .all: true + case .error: e.level == "error" + case .warn: e.level == "warn" + case .info: e.level == "info" + case .query: e.level == "query" + } + let t = window.seconds.map { e.time >= Date().addingTimeInterval(-$0) } ?? true + let s = search.isEmpty || e.message.localizedCaseInsensitiveContains(search) || (e.detail ?? "").localizedCaseInsensitiveContains(search) + return lvl && t && s + } + .sorted { $0.time > $1.time } + } + + private func load() async { + if bot.isDemo { entries = model.demoLogs(for: bot.id) ?? []; return } + guard let engine = model.engine else { error = model.engineProblem; return } + loading = true + defer { loading = false } + do { entries = try await engine.logs(model.target(for: bot), last: 300); error = nil } + catch { self.error = error as? EngineError ?? .failed(error.localizedDescription) } + } +} + +@MainActor struct LogRow: View { + let entry: LogEntry + let expanded: Bool + let toggle: () -> Void + let explain: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + HStack(alignment: .firstTextBaseline, spacing: Space.s) { + Text(entry.severity).font(.caption.weight(.bold).monospaced()) + .foregroundStyle(color).frame(width: 64, alignment: .leading) + Text(entry.time.formatted(date: .omitted, time: .standard)).font(.caption.monospacedDigit()).foregroundStyle(.secondary) + Text(entry.message).font(.system(.callout, design: .monospaced)).lineLimit(expanded ? nil : 1).textSelection(.enabled) + Spacer() + } + if expanded { + VStack(alignment: .leading, spacing: 4) { + if let d = entry.detail, !d.isEmpty { Text(d).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) } + Text([entry.user.map { "user \($0)" }, entry.database.map { "db \($0)" }, entry.app.map { "app \($0)" }, entry.pid.map { "pid \($0)" }] + .compactMap { $0 }.joined(separator: " · ")).font(.caption2).foregroundStyle(.tertiary) + HStack { + Button("Explain with PGBot", action: explain).buttonStyle(.borderedProminent) + Button("Copy") { Pasteboard.copy([entry.severity, entry.message, entry.detail ?? ""].joined(separator: "\n")) } + } + .controlSize(.small) + } + .padding(.leading, 72) + } + } + .padding(.vertical, 3) + .contentShape(Rectangle()) + .onTapGesture(perform: toggle) + .listRowBackground(entry.level == "error" ? Color.red.opacity(0.06) : (entry.level == "warn" ? Color.orange.opacity(0.05) : Color.clear)) + .contextMenu { + Button("Copy Message") { Pasteboard.copy(entry.message) } + Button("Explain with PGBot", action: explain) + } + } + + private var color: Color { + switch entry.severity.uppercased() { + case "PANIC", "FATAL", "ERROR": .red + case "WARNING": .orange + case "NOTICE", "INFO": .blue + case "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4", "DEBUG5": .secondary + default: .secondary + } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Metrics/MetricsView.swift b/desktop/macos/Sources/PGBot/Features/Metrics/MetricsView.swift new file mode 100644 index 0000000..f4eca00 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Metrics/MetricsView.swift @@ -0,0 +1,563 @@ +import Charts +import PGBotKit +import SwiftUI + +enum MetricsSection: String, CaseIterable, Identifiable { + case overview = "Overview", queries = "Queries", connections = "Connections", locks = "Locks & Waits" + case replication = "Replication", vacuum = "Vacuum", storage = "Storage", wal = "WAL", errors = "Errors" + case indexes = "Indexes", schema = "Schema", settings = "Settings" + var id: String { rawValue } + var symbol: String { + switch self { + case .overview: "square.grid.2x2" + case .queries: "bolt.horizontal" + case .connections: "person.2" + case .locks: "lock" + case .replication: "arrow.triangle.2.circlepath" + case .vacuum: "wind" + case .storage: "internaldrive" + case .wal: "waveform.path" + case .errors: "exclamationmark.bubble" + case .indexes: "list.bullet.indent" + case .schema: "tablecells" + case .settings: "slider.horizontal.3" + } + } +} + +enum TimeRange: String, CaseIterable, Identifiable { + case hour = "1H", sixHours = "6H", day = "24H", week = "7D", month = "30D" + var id: String { rawValue } + var seconds: TimeInterval { + switch self { case .hour: 3600; case .sixHours: 21600; case .day: 86400; case .week: 604_800; case .month: 2_592_000 } + } +} + +@MainActor struct MetricsView: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + @State private var section: MetricsSection = .overview + @State private var range: TimeRange = .day + @State private var customStart = Date().addingTimeInterval(-86400 * 3) + @State private var useCustom = false + + var body: some View { + VStack(spacing: 0) { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 4) { + ForEach(MetricsSection.allCases) { s in + Button { withAnimation(.snappy(duration: 0.2)) { section = s } } label: { + Text(s.rawValue) + .font(.sys(size: 13, weight: section == s ? .semibold : .regular)) + .foregroundStyle(section == s ? Color.primary : Color.secondary) + .padding(.horizontal, 12).frame(height: 30) + .background(section == s ? Palette.selection : .clear, in: Capsule()) + .contentShape(Capsule()) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 24) + } + .frame(maxWidth: .infinity) + .padding(.top, 4) + + ScrollView { + VStack(alignment: .leading, spacing: Space.l) { + HStack { + Text(section.rawValue).font(.sys(size: 24, weight: .semibold)) + Spacer() + if [.overview, .connections, .storage, .wal, .replication].contains(section) { + Picker("Range", selection: $range) { ForEach(TimeRange.allCases) { Text($0.rawValue).tag($0) } } + .pickerStyle(.segmented).labelsHidden().frame(width: 230).disabled(useCustom) + Toggle("Custom", isOn: $useCustom).toggleStyle(.checkbox) + if useCustom { DatePicker("", selection: $customStart, in: ...Date()).labelsHidden().frame(width: 170) } + } + } + content + } + .frame(maxWidth: 980) + .padding(.horizontal, 28).padding(.top, 18).padding(.bottom, 32) + .frame(maxWidth: .infinity) + } + } + } + + private var since: Date { useCustom ? customStart : Date().addingTimeInterval(-range.seconds) } + private var ctx: EngineContext? { model.latest[bot.id]?.context } + + @ViewBuilder private var content: some View { + if let ctx { + switch section { + case .overview: OverviewSection(bot: bot, ctx: ctx, record: model.latest[bot.id]!, since: since) + case .queries: QueriesSection(bot: bot, ctx: ctx) + case .connections: ConnectionsSection(bot: bot, ctx: ctx, since: since) + case .locks: LocksSection(ctx: ctx) + case .replication: ReplicationSectionView(bot: bot, ctx: ctx, since: since) + case .vacuum: VacuumSection(ctx: ctx) + case .storage: StorageSection(bot: bot, ctx: ctx, since: since) + case .wal: WALSectionView(bot: bot, ctx: ctx, since: since) + case .errors: ErrorsSection(bot: bot, ctx: ctx) + case .indexes: IndexesSectionView(ctx: ctx) + case .schema: SchemaSection(ctx: ctx) + case .settings: SettingsParamsSection(ctx: ctx) + } + } else { + ContentUnavailableView { + Label("No metrics yet", systemImage: "chart.xyaxis.line") + } description: { + Text("Metrics appear after the first inspection. History builds up as PGBot keeps monitoring.") + } actions: { + Button("Run inspection") { Task { await model.inspect(bot.id, reason: .manual) } } + } + .padding(.top, 60) + } + } +} + +// MARK: - Building blocks + +@MainActor struct MetricTile: View { + let title: String + let value: String? + var caption: String? = nil + var tint: Color = .primary + var unavailableReason: String? = nil + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text(title).font(.caption).foregroundStyle(.secondary) + if let value { + Text(value).font(.title2.weight(.semibold).monospacedDigit()).foregroundStyle(tint).lineLimit(1).minimumScaleFactor(0.7) + } else { + Text("Unavailable").font(.title3).foregroundStyle(.tertiary) + } + if let c = value == nil ? unavailableReason : caption { + Text(c).font(.caption2).foregroundStyle(.tertiary).lineLimit(2) + } + } + .frame(maxWidth: .infinity, minHeight: 72, alignment: .topLeading) + .card(padding: Space.m) + } +} + +@MainActor struct HistoryChart: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + let metric: MetricKey + let since: Date + var format: (Double) -> String = { String(format: "%.0f", $0) } + + var body: some View { + let points = (try? model.store.samples(for: bot.id, metric: metric, since: since)) ?? [] + VStack(alignment: .leading, spacing: Space.s) { + HStack { + Text(metric.label).font(.headline) + Spacer() + if let last = points.last { Text(format(last.value)).font(.callout.monospacedDigit()).foregroundStyle(.secondary) } + } + if points.count < 2 { + Text(points.isEmpty ? "No history in this range yet." : "One sample so far — the trend appears after the next inspection.") + .font(.callout).foregroundStyle(.tertiary).frame(maxWidth: .infinity, minHeight: 110) + } else { + Chart(points, id: \.at) { p in + AreaMark(x: .value("Time", p.at), y: .value(metric.label, p.value)) + .foregroundStyle(LinearGradient(colors: [bot.avatar.color.color.opacity(0.22), .clear], startPoint: .top, endPoint: .bottom)) + .interpolationMethod(.monotone) + LineMark(x: .value("Time", p.at), y: .value(metric.label, p.value)) + .foregroundStyle(bot.avatar.color.color).lineStyle(.init(lineWidth: 1.5)).interpolationMethod(.monotone) + } + .chartYAxis { AxisMarks(position: .leading) { v in + AxisGridLine().foregroundStyle(Palette.hairline) + AxisValueLabel { if let d = v.as(Double.self) { Text(format(d)).font(.caption2) } } + } } + .chartXAxis { AxisMarks { _ in AxisGridLine().foregroundStyle(.clear); AxisValueLabel().font(.caption2) } } + .chartOverlay { proxy in ChartHover(proxy: proxy, points: points, format: format) } + .frame(height: 140) + } + } + .card(padding: Space.m) + } +} + +/// Tooltip with timestamp and value under the pointer. +@MainActor struct ChartHover: View { + let proxy: ChartProxy + let points: [MetricPoint] + let format: (Double) -> String + @State private var hover: MetricPoint? + var body: some View { + GeometryReader { g in + Rectangle().fill(.clear).contentShape(Rectangle()) + .onContinuousHover { phase in + switch phase { + case .active(let loc): + guard let plot = proxy.plotFrame, let date: Date = proxy.value(atX: loc.x - g[plot].origin.x) else { return } + hover = points.min { abs($0.at.timeIntervalSince(date)) < abs($1.at.timeIntervalSince(date)) } + case .ended: hover = nil + } + } + .overlay(alignment: .topLeading) { + if let h = hover, let plot = proxy.plotFrame, let x = proxy.position(forX: h.at) { + let px = g[plot].origin.x + x + Rectangle().fill(Color.secondary.opacity(0.4)).frame(width: 1, height: g[plot].height).offset(x: px, y: g[plot].origin.y) + VStack(alignment: .leading, spacing: 1) { + Text(format(h.value)).font(.caption.weight(.semibold).monospacedDigit()) + Text(h.at.formatted(date: .abbreviated, time: .shortened)).font(.caption2).foregroundStyle(.secondary) + } + .padding(6).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 6)) + .offset(x: min(max(0, px - 50), g.size.width - 130), y: 0) + } + } + } + } +} + +@MainActor struct UnavailableNote: View { + let title: String + let reason: String + var body: some View { + Label { VStack(alignment: .leading, spacing: 2) { Text(title).font(.headline); Text(reason).foregroundStyle(.secondary) } } + icon: { Image(systemName: "eye.slash").foregroundStyle(.secondary) } + .frame(maxWidth: .infinity, alignment: .leading) + .card(padding: Space.m) + } +} + +let tileColumns = [GridItem(.adaptive(minimum: 170), spacing: Space.m)] + +// MARK: - Sections + +@MainActor struct OverviewSection: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + let ctx: EngineContext + let record: InspectionRecord + let since: Date + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + HealthScoreView(score: record.score, previous: model.previous[bot.id]?.score.value, + inspectedAt: record.finishedAt, bands: model.settings.bands).card() + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Active connections", value: ctx.activity?.active.map { "\($0)" }, caption: ctx.activity?.total.map { "\($0) total sessions" }) + MetricTile(title: "Connection utilization", + value: ctx.limits.map { "\($0.connectionsUsed)/\($0.connectionsMax)" }, + caption: ctx.limits?.utilization.map { Format.percent($0, digits: 0) + " of max_connections" }) + MetricTile(title: "Transactions / sec", value: ctx.health?.tps.map { String(format: "%.1f", $0) }, unavailableReason: ctx.health?.reason) + MetricTile(title: "Avg query time", + value: avgQueryMS.map(Format.ms), caption: "Across pg_stat_statements", + unavailableReason: ctx.queries?.reason ?? "Needs pg_stat_statements") + MetricTile(title: "Cache hit ratio", value: ctx.health?.cacheHitRatio.map { Format.percent($0) }, + tint: (ctx.health?.cacheHitRatio ?? 1) < 0.95 ? .orange : .primary) + MetricTile(title: "Database size", value: ctx.tables?.dbSizeBytes.map(Format.bytes)) + MetricTile(title: "Deadlocks / min", value: ctx.health?.deadlocksPerMin.map { String(format: "%.2f", $0) }) + MetricTile(title: "Rollback rate", value: ctx.health?.rollbackRatio.map { Format.percent($0, digits: 2) }) + MetricTile(title: "Replication lag", value: replicationLag, unavailableReason: "No replicas reporting") + MetricTile(title: "WAL generation", value: ctx.wal?.bytesPerSec.map { Format.bytes($0) + "/s" }, unavailableReason: ctx.wal?.reason) + MetricTile(title: "Autovacuum", value: ctx.activity?.autovacuumWorkers.map { "\($0) running" } ?? "Idle", + caption: ctx.findings.contains { $0.id.contains("vacuum") } ? "See Vacuum" : "No vacuum findings") + MetricTile(title: "Findings", value: "\(record.score.critical) critical · \(record.score.warnings) warn", + tint: record.score.critical > 0 ? .red : (record.score.warnings > 0 ? .orange : .primary)) + } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 340), spacing: Space.m)], spacing: Space.m) { + HistoryChart(bot: bot, metric: .healthScore, since: since) + HistoryChart(bot: bot, metric: .connections, since: since) + HistoryChart(bot: bot, metric: .tps, since: since) { String(format: "%.0f", $0) } + HistoryChart(bot: bot, metric: .cacheHitRatio, since: since) { Format.percent($0) } + } + UnavailableNote(title: "Infrastructure metrics (CPU, memory, disk, network)", + reason: "PGBot reads PostgreSQL over SQL only, so host metrics aren't measured here — and never estimated. Provider integrations (RDS/CloudWatch, Cloud SQL, Azure Monitor) will supply them in a future release.") + } + } + + private var avgQueryMS: Double? { + guard let top = ctx.queries?.top, !top.isEmpty, ctx.queries?.isAvailable == true else { return nil } + let calls = top.reduce(0) { $0 + $1.calls } + return calls > 0 ? top.reduce(0) { $0 + $1.totalMS } / Double(calls) : nil + } + + private var replicationLag: String? { + let lags = (ctx.replication?.replicas ?? []).compactMap(\.replayLagSec) + [ctx.replication?.receiverLagSec].compactMap { $0 } + return lags.max().map(Format.seconds) + } +} + +@MainActor struct QueriesSection: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + let ctx: EngineContext + @State private var sortOrder = [KeyPathComparator(\QueryStat.totalMS, order: .reverse)] + @State private var filter = "" + @State private var selected: QueryStat.ID? + + var body: some View { + if let q = ctx.queries, q.isAvailable, let top = q.top { + let rows = top.filter { filter.isEmpty || $0.query.localizedCaseInsensitiveContains(filter) }.sorted(using: sortOrder) + VStack(alignment: .leading, spacing: Space.m) { + TextField("Filter queries", text: $filter).textFieldStyle(.roundedBorder).frame(maxWidth: 300) + Table(rows, selection: $selected, sortOrder: $sortOrder) { + TableColumn("Query", value: \.query) { Text(Format.sqlPreview($0.query, limit: 120)).font(.system(.caption, design: .monospaced)) } + .width(min: 260, ideal: 420) + TableColumn("Total", value: \.totalMS) { Text(Format.ms($0.totalMS)).monospacedDigit() }.width(80) + TableColumn("Mean", value: \.meanMS) { Text(Format.ms($0.meanMS)).monospacedDigit() }.width(70) + TableColumn("Calls", value: \.calls) { Text(Format.count($0.calls)).monospacedDigit() }.width(70) + TableColumn("Cache hit") { Text($0.cacheHit.map { Format.percent($0) } ?? "—").monospacedDigit() }.width(70) + } + .frame(minHeight: 300) + if let id = selected, let qs = top.first(where: { $0.id == id }) { + VStack(alignment: .leading, spacing: Space.s) { + SQLBlock(sql: qs.query) + HStack { + Text("\(Format.count(qs.calls)) calls · mean \(Format.ms(qs.meanMS)) · max \(Format.ms(qs.maxMS ?? 0)) · \(Format.count(qs.rows ?? 0)) rows") + .font(.callout).foregroundStyle(.secondary) + Spacer() + Button("Explain SQL") { model.route = .chat; model.explain(sql: qs.query, on: bot.id) } + .disabled(!qs.query.lowercased().hasPrefix("select")) + Button("Ask PGBot") { model.route = .chat; model.send("Why is this query expensive, and what can I do about it? queryid \(qs.queryID)", to: bot.id) } + .buttonStyle(.borderedProminent) + } + } + .card(padding: Space.m) + } + Text("Normalized statements from pg_stat_statements; literals are replaced with placeholders.") + .font(.caption).foregroundStyle(.tertiary) + } + } else { + UnavailableNote(title: "Query statistics unavailable", + reason: (ctx.queries?.reason ?? "pg_stat_statements isn't enabled.") + " Enable the pg_stat_statements extension to see expensive and slow queries.") + } + } +} + +@MainActor struct ConnectionsSection: View { + let bot: DatabaseBot + let ctx: EngineContext + let since: Date + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Total", value: ctx.activity?.total.map { "\($0)" }) + MetricTile(title: "Active", value: ctx.activity?.active.map { "\($0)" }) + MetricTile(title: "Idle", value: ctx.activity?.idle.map { "\($0)" }) + MetricTile(title: "Idle in transaction", value: ctx.activity?.idleInTransaction.map { "\($0)" }, + caption: ctx.activity?.longestIdleXactSec.map { "Longest " + Format.seconds($0) }, + tint: (ctx.activity?.idleInTransaction ?? 0) > 0 ? .orange : .primary) + MetricTile(title: "Longest transaction", value: ctx.activity?.longestXactSec.map(Format.seconds)) + MetricTile(title: "max_connections", value: ctx.limits.map { "\($0.connectionsMax)" }) + } + HistoryChart(bot: bot, metric: .connections, since: since) + if let groups = ctx.activity?.connections, !groups.isEmpty { + TableCard(title: "Top connection sources", columns: ["Application", "User", "State", "Count"], + rows: groups.map { [$0.appName.isEmpty ? "—" : $0.appName, $0.user, $0.state, "\($0.count)"] }) + } + } + } +} + +@MainActor struct LocksSection: View { + let ctx: EngineContext + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Blocked sessions", value: ctx.locks?.blockedCount.map { "\($0)" }, + tint: (ctx.locks?.blockedCount ?? 0) > 0 ? .orange : .primary, unavailableReason: ctx.locks?.reason) + MetricTile(title: "Waiting sessions", value: ctx.activity?.waiting.map { "\($0)" }) + MetricTile(title: "Idle in transaction", value: ctx.activity?.idleInTransaction.map { "\($0)" }) + MetricTile(title: "Deadlocks / min", value: ctx.health?.deadlocksPerMin.map { String(format: "%.2f", $0) }) + } + if let chains = ctx.locks?.chains, !chains.isEmpty { + TableCard(title: "Blocking relationships", columns: ["Blocked", "Blocked by", "Wait", "Waiting", "Query"], + rows: chains.map { ["\($0.blockedPID)", $0.blockingPIDs.map(String.init).joined(separator: ", "), $0.waitEvent ?? "", Format.seconds($0.waitSeconds), Format.sqlPreview($0.blockedQuery)] }) + } else { + Label("No blocking chains at the last inspection.", systemImage: "checkmark.circle").foregroundStyle(.secondary) + } + if let wp = ctx.waitProfile { + if wp.available, let buckets = wp.buckets, !buckets.isEmpty { + VStack(alignment: .leading, spacing: Space.s) { + Text("Where time went (\(wp.samples ?? 0) samples over \(Format.seconds(wp.windowSeconds ?? 0)))").font(.headline) + Chart(buckets, id: \.type) { b in + BarMark(x: .value("Share", b.share), y: .value("Wait", b.type)) + .annotation(position: .trailing) { Text(Format.percent(b.share, digits: 0)).font(.caption2).foregroundStyle(.secondary) } + } + .chartXAxis(.hidden) + .frame(height: CGFloat(buckets.count) * 26 + 10) + } + .card(padding: Space.m) + } else { + UnavailableNote(title: "Wait sampling unavailable", reason: wp.reason ?? "No samples captured.") + } + } + } + } +} + +@MainActor struct ReplicationSectionView: View { + let bot: DatabaseBot + let ctx: EngineContext + let since: Date + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + if let r = ctx.replication, r.isAvailable { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Role", value: r.isReplica == true ? "Standby" : "Primary") + MetricTile(title: "Replicas", value: "\(r.replicas?.count ?? 0)") + MetricTile(title: "Slots", value: "\(r.slots?.count ?? 0)", caption: "\(r.slots?.filter { !$0.active }.count ?? 0) inactive", + tint: (r.slots?.contains { !$0.active } ?? false) ? .orange : .primary) + MetricTile(title: "Retained WAL", value: Format.bytes((r.slots ?? []).reduce(0) { $0 + $1.retainedBytes })) + } + HistoryChart(bot: bot, metric: .replicationLagSec, since: since) { Format.seconds($0) } + if let reps = r.replicas, !reps.isEmpty { + TableCard(title: "Replicas", columns: ["Name", "State", "Sync", "Replay lag", "Bytes behind"], + rows: reps.map { [$0.appName ?? $0.clientAddr, $0.state, $0.syncState, $0.replayLagSec.map(Format.seconds) ?? "idle", Format.bytes($0.replayLagBytes ?? 0)] }) + } + if let slots = r.slots, !slots.isEmpty { + TableCard(title: "Replication slots", columns: ["Slot", "Type", "Active", "Retained", "WAL status"], + rows: slots.map { [$0.name, $0.type, $0.active ? "yes" : "no", Format.bytes($0.retainedBytes), $0.walStatus ?? "—"] }) + } + } else { + UnavailableNote(title: "Replication unavailable", reason: ctx.replication?.reason ?? "Not collected.") + } + } + } +} + +@MainActor struct VacuumSection: View { + let ctx: EngineContext + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Transaction ID age", value: ctx.limits?.maxXIDAge.map { Format.count($0) }, + caption: ctx.limits?.wraparoundFraction.map { Format.percent($0) + " of the wraparound limit" }, + tint: (ctx.limits?.wraparoundFraction ?? 0) > 0.5 ? .orange : .primary) + MetricTile(title: "Autovacuum workers", value: ctx.activity?.autovacuumWorkers.map { "\($0)" } ?? "0") + MetricTile(title: "Dead tuples (top tables)", value: Format.count((ctx.tables?.top ?? []).reduce(0) { $0 + $1.deadTuples })) + } + let tables = (ctx.tables?.top ?? []).sorted { $0.deadRatio > $1.deadRatio } + if !tables.isEmpty { + TableCard(title: "Tables", columns: ["Table", "Dead", "Dead %", "Last vacuum", "Last analyze"], + rows: tables.map { [$0.id, Format.count($0.deadTuples), Format.percent($0.deadRatio), + $0.lastAnyVacuum.map { $0.formatted(.relative(presentation: .named)) } ?? "never", + [$0.lastAnalyze, $0.lastAutoanalyze].compactMap { $0 }.max().map { $0.formatted(.relative(presentation: .named)) } ?? "never"] }) + } + let vf = ctx.findings.filter { ($0.id.contains("vacuum") || $0.id.contains("bloat") || $0.id.contains("wraparound")) && !$0.isSuppressed } + ForEach(vf, id: \.key) { FindingLine(finding: $0) } + } + } +} + +@MainActor struct StorageSection: View { + let bot: DatabaseBot + let ctx: EngineContext + let since: Date + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Database size", value: ctx.tables?.dbSizeBytes.map(Format.bytes)) + MetricTile(title: "Potentially unused indexes", value: "\(ctx.indexes?.unused?.count ?? 0)", + caption: Format.bytes((ctx.indexes?.unused ?? []).reduce(0) { $0 + $1.bytes })) + } + HistoryChart(bot: bot, metric: .dbSizeBytes, since: since) { Format.bytes($0) } + if let top = ctx.tables?.top, !top.isEmpty { + VStack(alignment: .leading, spacing: Space.s) { + Text("Largest tables").font(.headline) + Chart(top.prefix(10)) { t in + BarMark(x: .value("Size", t.totalBytes), y: .value("Table", t.id)) + .foregroundStyle(bot.avatar.color.color.opacity(0.8)) + .annotation(position: .trailing) { Text(Format.bytes(t.totalBytes)).font(.caption2).foregroundStyle(.secondary) } + } + .chartXAxis(.hidden).frame(height: CGFloat(min(top.count, 10)) * 26 + 10) + } + .card(padding: Space.m) + } + Text("Sizes include indexes and TOAST storage (pg_total_relation_size).").font(.caption).foregroundStyle(.tertiary) + } + } +} + +@MainActor struct WALSectionView: View { + let bot: DatabaseBot + let ctx: EngineContext + let since: Date + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "WAL generation", value: ctx.wal?.bytesPerSec.map { Format.bytes($0) + "/s" }, unavailableReason: ctx.wal?.reason) + MetricTile(title: "pg_wal directory", value: ctx.wal?.dirBytes.map(Format.bytes), unavailableReason: "Needs pg_monitor (pg_ls_waldir)") + } + HistoryChart(bot: bot, metric: .walBytesPerSec, since: since) { Format.bytes($0) + "/s" } + } + } +} + +@MainActor struct ErrorsSection: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + let ctx: EngineContext + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Rollback rate", value: ctx.health?.rollbackRatio.map { Format.percent($0, digits: 2) }) + MetricTile(title: "Deadlocks / min", value: ctx.health?.deadlocksPerMin.map { String(format: "%.2f", $0) }) + } + UnavailableNote(title: "Error events come from the server log", + reason: "PostgreSQL statistics count rollbacks and deadlocks, but not individual errors, timeouts or failed logins. The Logs view reads them over SQL when the monitoring role can read the log; managed providers like Supabase and Neon expose logs through their own APIs.") + Button("Open Logs") { model.route = .logs }.buttonStyle(.bordered) + } + } +} + +@MainActor struct IndexesSectionView: View { + let ctx: EngineContext + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + if let ix = ctx.indexes, ix.isAvailable { + LazyVGrid(columns: tileColumns, spacing: Space.m) { + MetricTile(title: "Indexes", value: "\(ix.total ?? 0)") + MetricTile(title: "Potentially unused", value: "\(ix.unused?.count ?? 0)", caption: Format.bytes((ix.unused ?? []).reduce(0) { $0 + $1.bytes })) + } + if let u = ix.unused, !u.isEmpty { + TableCard(title: "Potentially unused indexes", columns: ["Index", "Table", "Size", "Scans"], + rows: u.map { [$0.id, $0.table, Format.bytes($0.bytes), Format.count($0.scans)] }) + Text("Zero scans since statistics were last reset. Check every replica before removing an index — PGBot never drops anything.") + .font(.caption).foregroundStyle(.secondary) + } + if let l = ix.largest, !l.isEmpty { + TableCard(title: "Largest indexes", columns: ["Index", "Table", "Size", "Scans"], + rows: l.map { [$0.id, $0.table, Format.bytes($0.bytes), Format.count($0.scans)] }) + } + } else { + UnavailableNote(title: "Index statistics unavailable", reason: ctx.indexes?.reason ?? "Not collected.") + } + } + } +} + +@MainActor struct SchemaSection: View { + let ctx: EngineContext + var body: some View { + VStack(alignment: .leading, spacing: Space.l) { + if let t = ctx.tables?.top, !t.isEmpty { + TableCard(title: "Tables (largest first)", columns: ["Table", "Rows", "Size", "Seq scans", "Index scans"], + rows: t.map { [$0.id, Format.count($0.liveTuples), Format.bytes($0.totalBytes), Format.count($0.seqScans ?? 0), Format.count($0.indexScans ?? 0)] }) + } + Text("For a full ER diagram, run `pgbot erd` in a terminal.").font(.caption).foregroundStyle(.tertiary) + } + } +} + +@MainActor struct SettingsParamsSection: View { + let ctx: EngineContext + var body: some View { + if let s = ctx.settings, s.isAvailable { + VStack(alignment: .leading, spacing: Space.l) { + if let p = s.params, !p.isEmpty { + TableCard(title: "Tuning parameters", columns: ["Setting", "Value"], rows: p.sorted { $0.key < $1.key }.map { [$0.key, $0.value] }) + } + if let o = s.overrides, !o.isEmpty { + TableCard(title: "Changed from defaults", columns: ["Setting", "Value"], rows: o.sorted { $0.key < $1.key }.map { [$0.key, $0.value] }) + } + } + } else { + UnavailableNote(title: "Settings unavailable", reason: ctx.settings?.reason ?? "Not collected.") + } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Notifications/NotificationCenterView.swift b/desktop/macos/Sources/PGBot/Features/Notifications/NotificationCenterView.swift new file mode 100644 index 0000000..a60d252 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Notifications/NotificationCenterView.swift @@ -0,0 +1,237 @@ +import PGBotKit +import SwiftUI + +@MainActor struct NotificationCenterView: View { + @Environment(AppModel.self) private var model + var initialBot: UUID? = nil + @State private var botFilter: UUID? + @State private var severityFilter: Severity? + @State private var unreadOnly = false + + var body: some View { + VStack(spacing: 0) { + HStack { + Text("Notifications").font(.headline) + Spacer() + Button("Mark all as read") { model.markAllRead() }.buttonStyle(.link).disabled(model.unreadNotifications == 0) + } + .padding(Space.m) + HStack(spacing: Space.s) { + Picker("Database", selection: $botFilter) { + Text("All databases").tag(UUID?.none) + ForEach(model.bots) { Text($0.displayName).tag(UUID?.some($0.id)) } + } + .labelsHidden() + Picker("Severity", selection: $severityFilter) { + Text("Any severity").tag(Severity?.none) + ForEach(Severity.allCases.reversed(), id: \.self) { Text($0.label).tag(Severity?.some($0)) } + } + .labelsHidden() + Toggle("Unread", isOn: $unreadOnly).toggleStyle(.checkbox) + } + .controlSize(.small).padding(.horizontal, Space.m).padding(.bottom, Space.s) + Divider() + if filtered.isEmpty { + ContentUnavailableView("You're all caught up", systemImage: "bell.badge", description: Text("New findings, regressions and resolutions appear here.")) + .frame(height: 260) + } else { + ScrollView { + LazyVStack(spacing: 0) { + ForEach(filtered) { n in + NotificationRow(n: n).onTapGesture { model.open(n) } + Divider().padding(.leading, 56) + } + } + } + .frame(maxHeight: 440) + } + Divider() + HStack { + if let id = botFilter, let bot = model.bot(id) { + Button(bot.muted ? "Unmute \(bot.displayName)" : "Mute \(bot.displayName)") { model.mutate(bot.id) { $0.muted.toggle() } } + } + Spacer() + Button("Notification settings…") { openAppSettings(tab: "notifications") } + } + .buttonStyle(.link).font(.callout).padding(Space.m) + } + .frame(width: 400) + .onAppear { botFilter = initialBot } + } + + private var filtered: [AppNotification] { + model.notifications.filter { + (botFilter == nil || $0.botID == botFilter) && (severityFilter == nil || $0.severity == severityFilter) && (!unreadOnly || !$0.read) + } + } +} + +@MainActor struct NotificationRow: View { + @Environment(AppModel.self) private var model + let n: AppNotification + var body: some View { + HStack(alignment: .top, spacing: Space.m) { + if let bot = model.bot(n.botID) { BotAvatarView(bot: bot, size: 32) } else { ElephantAvatar(color: .gray, size: 32) } + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 4) { + Image(systemName: n.category == .resolved ? "checkmark.circle.fill" : n.severity.symbol) + .foregroundStyle(n.category == .resolved ? .green : n.severity.color).font(.caption) + Text(n.title).font(.callout.weight(n.read ? .regular : .semibold)).lineLimit(1) + } + Text(n.body).font(.callout).foregroundStyle(.secondary).lineLimit(2) + Text(n.createdAt.formatted(.relative(presentation: .named))).font(.caption2).foregroundStyle(.tertiary) + } + Spacer() + if !n.read { Circle().fill(Theme.accent).frame(width: 7, height: 7).padding(.top, 6) } + } + .padding(.horizontal, Space.m).padding(.vertical, Space.s) + .contentShape(Rectangle()) + .hoverHighlight(cornerRadius: 0) + .contextMenu { + Button(n.read ? "Already read" : "Mark as Read") { model.markRead(n) }.disabled(n.read) + if let bot = model.bot(n.botID) { + Button(bot.muted ? "Unmute \(bot.displayName)" : "Mute \(bot.displayName)") { model.mutate(bot.id) { $0.muted.toggle() } } + } + } + .accessibilityElement(children: .combine) + .accessibilityHint("Opens the conversation") + } +} + +// MARK: - Menu bar + +@MainActor struct MenuBarContent: View { + @Environment(AppModel.self) private var model + @Environment(\.openWindow) private var openWindow + + var body: some View { + if model.session == nil { + VStack(alignment: .leading, spacing: Space.s) { + Text("PGBot").font(.headline) + Button("Open PGBot to sign in") { NSApp.activate(ignoringOtherApps: true); openWindow(id: "main") } + Button("Quit PGBot") { NSApp.terminate(nil) }.buttonStyle(.link).font(.caption) + } + .padding(Space.m).frame(width: 240) + } else { + signedIn + } + } + + private var signedIn: some View { + VStack(alignment: .leading, spacing: Space.s) { + HStack { + PGBotLogo(size: 22) + VStack(alignment: .leading, spacing: 0) { + Text("PGBot").font(.headline) + Text("\(model.bots.count) connected database\(model.bots.count == 1 ? "" : "s")").font(.caption).foregroundStyle(.secondary) + } + Spacer() + let crit = model.latest.values.reduce(0) { $0 + $1.score.critical } + let warn = model.latest.values.reduce(0) { $0 + $1.score.warnings } + VStack(alignment: .trailing, spacing: 0) { + Text("\(crit) critical").font(.caption).foregroundStyle(crit > 0 ? .red : .secondary) + Text("\(warn) warnings").font(.caption).foregroundStyle(warn > 0 ? .orange : .secondary) + } + } + Divider() + ForEach(model.bots) { bot in + Button { open(bot.id) } label: { + HStack(spacing: Space.s) { + StatusDot(status: bot.status) + Text(bot.displayName).lineLimit(1) + Spacer() + Text(bot.lastSummary.map { $0.components(separatedBy: " · ").first ?? $0 } ?? bot.status.label) + .font(.caption).foregroundStyle(.secondary).lineLimit(1) + } + .contentShape(Rectangle()) + } + .buttonStyle(.plain).padding(.vertical, 2) + } + if !model.notifications.isEmpty { + Divider() + Text("Recent").font(.caption.weight(.semibold)).foregroundStyle(.secondary) + ForEach(model.notifications.prefix(3)) { n in + Button { NSApp.activate(ignoringOtherApps: true); openWindow(id: "main"); model.open(n) } label: { + Text(n.body).font(.caption).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading) + }.buttonStyle(.plain) + } + } + Divider() + Text(model.monitoringPaused ? "Monitoring paused" : "Monitoring while this Mac is awake") + .font(.caption).foregroundStyle(.secondary) + HStack { + Button("Open PGBot") { NSApp.activate(ignoringOtherApps: true); openWindow(id: "main") } + Button("Run all") { model.runAllInspections() } + Button("Send test") { model.sendTestNotification() } + Button(model.monitoringPaused ? "Resume" : "Pause") { model.setMonitoringPaused(!model.monitoringPaused) } + } + .controlSize(.small) + HStack { + Button("Settings…") { NSApp.activate(ignoringOtherApps: true); openAppSettings() } + Spacer() + Button("Quit PGBot") { NSApp.terminate(nil) } + } + .buttonStyle(.link).font(.caption) + } + .padding(Space.m) + .frame(width: 320) + } + + private func open(_ id: UUID) { + NSApp.activate(ignoringOtherApps: true) + openWindow(id: "main") + model.selection = id + model.route = .chat + } +} + +// MARK: - Sheets + +/// Explicit consent before findings are sent to an external AI provider. +@MainActor struct AIConsentSheet: View { + @Environment(AppModel.self) private var model + let consent: AppModel.PendingConsent + var body: some View { + VStack(alignment: .leading, spacing: Space.m) { + Label("Send findings to \(consent.ai.provider.label)?", systemImage: "hand.raised").font(.title3.weight(.semibold)) + Text("To answer, PGBot sends this database's **findings** — the same PII-free report as `pgbot inspect --json` — and your question to \(consent.ai.provider.label)\(consent.ai.effectiveBaseURL.flatMap { URL(string: $0)?.host }.map { " at \($0)" } ?? "").") + VStack(alignment: .leading, spacing: 4) { + Label("Never sent: passwords, connection strings, or table contents", systemImage: "checkmark.shield") + Label("SQL literals are replaced with placeholders by the engine", systemImage: "checkmark.shield") + Label("The model can't reach your database; it only reads the findings", systemImage: "checkmark.shield") + } + .font(.callout).foregroundStyle(.secondary) + Text("You can revoke this in Settings → AI providers, or use Ollama to keep everything on this Mac.") + .font(.caption).foregroundStyle(.tertiary) + HStack { + Spacer() + Button("Cancel", role: .cancel) { model.pendingConsent = nil }.keyboardShortcut(.cancelAction) + Button("Allow and Ask") { model.grantConsent(consent) }.keyboardShortcut(.defaultAction).buttonStyle(.borderedProminent) + } + } + .padding(Space.xl).frame(width: 480) + } +} + +@MainActor struct ExplainSQLSheet: View { + @Environment(AppModel.self) private var model + @State private var sql = "" + var body: some View { + VStack(alignment: .leading, spacing: Space.m) { + Text("Explain SQL").font(.title3.weight(.semibold)) + Text("PGBot plans the query inside a read-only transaction and never executes it. Only a single SELECT is accepted.") + .foregroundStyle(.secondary) + TextEditor(text: $sql).font(.system(.body, design: .monospaced)).frame(height: 180) + .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(Palette.hairline)) + HStack { + Spacer() + Button("Cancel", role: .cancel) { model.explainSQLDraft = nil }.keyboardShortcut(.cancelAction) + Button("Explain") { if let id = model.selection { model.explain(sql: sql, on: id) } } + .keyboardShortcut(.defaultAction).buttonStyle(.borderedProminent) + .disabled(sql.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding(Space.xl).frame(width: 560) + .onAppear { sql = model.explainSQLDraft ?? "" } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Onboarding/AddDatabaseSheet.swift b/desktop/macos/Sources/PGBot/Features/Onboarding/AddDatabaseSheet.swift new file mode 100644 index 0000000..b788727 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Onboarding/AddDatabaseSheet.swift @@ -0,0 +1,264 @@ +import PGBotKit +import SwiftUI + +@MainActor struct AddDatabaseSheet: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + + enum Mode: String, CaseIterable { case url = "Connection URL", manual = "Manual" } + enum TestState { case idle, testing, success(EngineContext), failure(EngineError) } + + @State private var mode: Mode = .url + @State private var url = "" + @State private var urlError: String? + @State private var conn = DatabaseConnection() + @State private var password = "" + @State private var name = "" + @State private var description = "" + @State private var color: BotColor = BotColor.allCases.randomElement() ?? .blue + @State private var shape: AvatarShape = .roundedSquare + @State private var environment: DatabaseEnvironment = .production + @State private var test: TestState = .idle + @State private var testTask: Task? + @State private var setupSQL: String? + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: Space.m) { + ElephantAvatar(color: color, shape: shape, size: 44) + VStack(alignment: .leading) { + Text("Add database").font(.title2.weight(.semibold)) + Text("PGBot connects read-only and never changes your data.").foregroundStyle(.secondary) + } + Spacer() + } + .padding(Space.xl) + Divider() + ScrollView { + VStack(alignment: .leading, spacing: Space.xl) { + connectionSection + readOnlyAdvice + personalizeSection + } + .padding(Space.xl) + } + Divider() + footer.padding(Space.l) + } + .frame(width: 620, height: 720) + .sheet(isPresented: Binding(get: { setupSQL != nil }, set: { if !$0 { setupSQL = nil } })) { + SetupSQLSheet(sql: setupSQL ?? "") + } + .onAppear(perform: applyDefaults) + .onDisappear { testTask?.cancel() } + } + + // MARK: Sections + + private var connectionSection: some View { + VStack(alignment: .leading, spacing: Space.m) { + Picker("", selection: $mode) { ForEach(Mode.allCases, id: \.self) { Text($0.rawValue) } } + .pickerStyle(.segmented).labelsHidden().frame(width: 280) + .onChange(of: mode) { _, new in if new == .manual { applyURL() } } + if mode == .url { + VStack(alignment: .leading, spacing: 6) { + TextField("postgresql://username:password@hostname:5432/database?sslmode=require", text: $url, axis: .vertical) + .font(.system(.body, design: .monospaced)).lineLimit(1...3) + .textFieldStyle(.roundedBorder) + .onChange(of: url) { _, _ in applyURL(); test = .idle } + if let urlError { Text(urlError).font(.caption).foregroundStyle(.red) } + else if !url.isEmpty { + Text("\(conn.safeSummary) · SSL \(conn.sslMode.rawValue)\(password.isEmpty ? "" : " · password saved to Keychain")") + .font(.caption).foregroundStyle(.secondary) + } + Text("Supabase, Neon, RDS, Aurora, Cloud SQL, Azure, Render, Railway, PGBox or self-hosted — paste the URL your provider shows.") + .font(.caption).foregroundStyle(.tertiary) + } + } else { + Form { + TextField("Host", text: $conn.host) + TextField("Port", value: $conn.port, format: .number.grouping(.never)) + TextField("Database", text: $conn.database) + TextField("Username", text: $conn.username) + SecureField("Password", text: $password) + Picker("SSL mode", selection: $conn.sslMode) { ForEach(SSLMode.allCases) { Text($0.rawValue).tag($0) } } + Stepper("Connection timeout: \(conn.connectTimeoutSeconds)s", value: $conn.connectTimeoutSeconds, in: 2...120) + } + .formStyle(.columns) + .onChange(of: conn) { _, _ in test = .idle } + } + testResult + } + } + + @ViewBuilder private var testResult: some View { + switch test { + case .idle: EmptyView() + case .testing: + HStack(spacing: Space.s) { + ProgressView().controlSize(.small) + Text("Connecting and running a read-only inspection…").foregroundStyle(.secondary) + } + case .success(let ctx): + VStack(alignment: .leading, spacing: 4) { + Label("Connected to \(ctx.server.displayVersion)", systemImage: "checkmark.circle.fill").foregroundStyle(.green).font(.headline) + capability("pg_monitor role", ctx.server.hasPgMonitor ?? false, fix: "Grant pg_monitor to see sessions, locks and settings.") + capability("pg_stat_statements", ctx.queries?.isAvailable ?? false, fix: "Enable it for query analysis.") + capability("Read-only session", true, fix: "") + if let p = ctx.server.provider, !p.isEmpty, p != "unknown" { Text("Provider detected: \(p.uppercased())").font(.caption).foregroundStyle(.secondary) } + } + .card(padding: Space.m) + case .failure(let e): + VStack(alignment: .leading, spacing: 4) { + Label(e.title, systemImage: "xmark.octagon.fill").foregroundStyle(.red).font(.headline) + Text(e.hint) + if !e.detail.isEmpty { Text(e.detail).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) } + } + .card(padding: Space.m) + } + } + + private func capability(_ name: String, _ ok: Bool, fix: String) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Image(systemName: ok ? "checkmark" : "exclamationmark.triangle.fill").foregroundStyle(ok ? .green : .orange).font(.caption) + Text(name).font(.callout) + if !ok { Text("— \(fix)").font(.caption).foregroundStyle(.secondary) } + } + } + + private var readOnlyAdvice: some View { + HStack(alignment: .top, spacing: Space.m) { + Image(systemName: "lock.shield").font(.title2).foregroundStyle(.secondary) + VStack(alignment: .leading, spacing: 4) { + Text("Use a dedicated read-only role").font(.headline) + Text("PGBot only needs pg_monitor. A separate role keeps it away from your data and is easy to revoke.") + .foregroundStyle(.secondary) + Button("Show setup SQL") { Task { await loadSetupSQL() } }.buttonStyle(.link).disabled(model.engine == nil) + } + } + } + + private var personalizeSection: some View { + VStack(alignment: .leading, spacing: Space.m) { + Text("Personalize").font(.headline) + Form { + TextField("Display name", text: $name, prompt: Text(conn.database.isEmpty ? "My database" : conn.database)) + TextField("Description", text: $description, prompt: Text("Optional")) + Picker("Environment", selection: $environment) { ForEach(DatabaseEnvironment.allCases) { Text($0.label).tag($0) } } + Picker("Avatar shape", selection: $shape) { + Text("Rounded square").tag(AvatarShape.roundedSquare) + Text("Circle").tag(AvatarShape.circle) + } + .pickerStyle(.segmented) + LabeledContent("Color") { ColorSwatches(selection: $color, shape: shape) } + } + .formStyle(.columns) + } + } + + private var footer: some View { + HStack { + Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction) + Spacer() + Button("Test Connection") { runTest() }.disabled(!canConnect || isTesting) + Button("Add Database") { add() }.keyboardShortcut(.defaultAction).buttonStyle(.borderedProminent) + .disabled(!canConnect || isTesting) + } + } + + // MARK: Actions + + private var isTesting: Bool { if case .testing = test { return true }; return false } + private var canConnect: Bool { urlError == nil && !conn.host.isEmpty && (mode == .manual || !url.isEmpty) } + + /// Settings → New Databases. + private func applyDefaults() { + let d = model.settings + conn.sslMode = d.defaultSSLMode + conn.connectTimeoutSeconds = d.defaultConnectTimeout + environment = d.defaultEnvironment + shape = d.defaultAvatarShape + if let c = d.defaultAvatarColor { color = c } + } + + private func applyURL() { + guard !url.trimmingCharacters(in: .whitespaces).isEmpty else { urlError = nil; return } + do { + let p = try ConnectionString.parse(url) + conn = p.connection + password = p.password ?? "" + urlError = nil + if conn.host.contains("supabase") { color = .green } else if conn.host.contains("neon") { color = .teal } + if ["localhost", "127.0.0.1", "::1"].contains(conn.host) { environment = .local } + } catch { + urlError = (error as? LocalizedError)?.errorDescription ?? "Couldn't read that URL." + } + } + + private func runTest() { + guard let engine = model.engine else { test = .failure(model.engineProblem ?? .engineMissing("")); return } + test = .testing + let target = EngineTarget(connection: conn, password: password.isEmpty ? nil : password) + testTask = Task { + do { let ctx = try await engine.inspect(target); if !Task.isCancelled { test = .success(ctx) } } + catch { if !Task.isCancelled { test = .failure(error as? EngineError ?? .failed(error.localizedDescription)) } } + } + } + + private func add() { + if model.demoMode { model.setDemoMode(false) } + let displayName = name.trimmingCharacters(in: .whitespaces).isEmpty ? conn.database : name + let bot = DatabaseBot(displayName: displayName, description: description, + avatar: BotAvatar(color: color, shape: shape), environment: environment, + connection: conn, pinned: model.bots.filter(\.pinned).count < 3, + schedule: { + var s = MonitoringSchedule() + s.intervalSeconds = model.settings.defaultIntervalSeconds + s.dailyReportHour = model.settings.defaultDailyReportHour + s.retentionDays = model.settings.defaultRetentionDays + return s + }()) + var first: EngineContext? + if case .success(let ctx) = test { first = ctx } + model.addBot(bot, password: password.isEmpty ? nil : password, firstInspection: first) + dismiss() + } + + private func loadSetupSQL() async { + guard let engine = model.engine else { return } + setupSQL = (try? await engine.setupSQL(role: "pgbot_ro", database: conn.database.isEmpty ? "postgres" : conn.database, includeLogs: false)) + ?? "-- Couldn't generate setup SQL. Run `pgbot init` in a terminal." + } +} + +@MainActor struct ColorSwatches: View { + @Binding var selection: BotColor + var shape: AvatarShape = .roundedSquare + var body: some View { + HStack(spacing: 6) { + ForEach(BotColor.allCases) { c in + Button { selection = c } label: { + ElephantAvatar(color: c, shape: shape, size: 26) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(selection == c ? Theme.accent : .clear, lineWidth: 2).padding(-3)) + } + .buttonStyle(.plain).help(c.label).accessibilityLabel(c.label) + .accessibilityAddTraits(selection == c ? .isSelected : []) + } + } + } +} + +@MainActor struct SetupSQLSheet: View { + let sql: String + @Environment(\.dismiss) private var dismiss + var body: some View { + VStack(alignment: .leading, spacing: Space.m) { + Text("Create a read-only monitoring role").font(.title3.weight(.semibold)) + Text("Generated by `pgbot init`. Review it, set a real password, and run it as an administrator. PGBot never runs it for you.") + .foregroundStyle(.secondary) + ScrollView { SQLBlock(sql: sql) } + HStack { Spacer(); Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) } + } + .padding(Space.xl).frame(width: 640, height: 520) + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Onboarding/OnboardingView.swift b/desktop/macos/Sources/PGBot/Features/Onboarding/OnboardingView.swift new file mode 100644 index 0000000..47c14e3 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Onboarding/OnboardingView.swift @@ -0,0 +1,32 @@ +import PGBotKit +import SwiftUI + +@MainActor struct OnboardingView: View { + @Environment(AppModel.self) private var model + + var body: some View { + VStack(spacing: Space.xl) { + HStack(spacing: -10) { + ElephantAvatar(color: .blue, size: 56).rotationEffect(.degrees(-8)) + ElephantAvatar(color: .green, size: 72).zIndex(1) + ElephantAvatar(color: .orange, size: 56).rotationEffect(.degrees(8)) + } + VStack(spacing: Space.s) { + Text("Meet your first database bot.").font(.sys(size: 28, weight: .semibold)) + Text("Connect a PostgreSQL database and PGBot will analyze its health, identify potential issues, and help you understand what to improve.") + .font(.title3).foregroundStyle(.secondary).multilineTextAlignment(.center).frame(maxWidth: 520) + } + Button { model.showingAddDatabase = true } label: { + Label("Add database", systemImage: "plus").font(.headline).padding(.horizontal, Space.l).frame(height: 36) + } + .buttonStyle(.borderedProminent).controlSize(.large) + .keyboardShortcut(.defaultAction) + + Text("Works with local PostgreSQL, Supabase, Neon, AWS RDS & Aurora, Google Cloud SQL, Azure, Render, Railway, PGBox and self-hosted servers.") + .font(.callout).foregroundStyle(.tertiary).multilineTextAlignment(.center).frame(maxWidth: 520) + Button("Explore with sample data") { model.setDemoMode(true) }.buttonStyle(.link).font(.callout) + } + .padding(Space.xxl) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Settings/AppSettingsView.swift b/desktop/macos/Sources/PGBot/Features/Settings/AppSettingsView.swift new file mode 100644 index 0000000..420c913 --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Settings/AppSettingsView.swift @@ -0,0 +1,530 @@ +import PGBotKit +import SwiftUI + +/// The native Settings window (⌘,). +@MainActor struct AppSettingsView: View { + @AppStorage("settingsTab") private var tab = "account" + + private static let sections: [(id: String, title: String, symbol: String)] = [ + ("account", "Account", "person.crop.circle"), + ("appearance", "Appearance", "paintbrush"), + ("defaults", "New Databases", "cylinder.split.1x2"), + ("monitoring", "Monitoring", "waveform.path.ecg"), + ("ai", "AI Providers", "sparkles"), + ("notifications", "Notifications", "bell"), + ("integrations", "Integrations", "puzzlepiece.extension"), + ("privacy", "Privacy & Security", "lock.shield"), + ("about", "About", "info.circle"), + ] + + var body: some View { + HStack(spacing: 0) { + List(selection: Binding(get: { tab }, set: { tab = $0 ?? "account" })) { + ForEach(Self.sections, id: \.id) { s in + Label(s.title, systemImage: s.symbol).tag(s.id) + } + } + .listStyle(.sidebar) + .frame(width: 200) + Divider() + VStack(alignment: .leading, spacing: 0) { + Text(Self.sections.first { $0.id == tab }?.title ?? "") + .font(.system(size: 20, weight: .semibold)) + .padding(.horizontal, 22).padding(.top, 18) + detail.frame(maxWidth: .infinity, maxHeight: .infinity) + } + .background(Palette.canvas) + } + .frame(width: 800, height: 600) + } + + @ViewBuilder private var detail: some View { + switch tab { + case "appearance": AppearanceSettings() + case "defaults": NewDatabaseSettings() + case "monitoring": MonitoringSettings() + case "ai": AIProviderSettings() + case "notifications": NotificationSettings() + case "integrations": IntegrationSettings() + case "privacy": PrivacySettings() + case "about": AboutSettings() + default: AccountSettings() + } + } +} + +@MainActor private struct AccountSettings: View { + @Environment(AppModel.self) private var model + var body: some View { + Form { + if let s = model.session { + HStack(spacing: Space.m) { + ProfileAvatar(name: s.user.name, size: 48) + VStack(alignment: .leading) { + Text(s.user.name).font(.headline) + Text(s.user.email ?? (s.user.provider == .local ? "Local profile — no account" : "")).foregroundStyle(.secondary) + } + } + LabeledContent("Signed in with", value: s.user.provider == .local ? "Not signed in (local only)" : s.user.provider.rawValue.capitalized) + LabeledContent("Plan", value: s.subscription.plan == .pro ? "Pro" : "Free") + Section { + Text("Free includes unlimited local database bots, diagnostics, monitoring, metrics, logs and bring-your-own AI. Pro will add always-on cloud monitoring, Slack/email/webhooks and team features.") + .font(.callout).foregroundStyle(.secondary) + Link("Manage subscription", destination: URL(string: "https://pgbot.dev/pricing")!) + } + Section { + Button("Sign Out") { Task { await model.signOut() } } + } + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +@MainActor private struct AppearanceSettings: View { + @Environment(AppModel.self) private var model + var body: some View { + @Bindable var model = model + Form { + Section("Look") { + Picker("Theme", selection: $model.settings.appearance) { + Text("System").tag(AppSettings.Appearance.system) + Text("Light").tag(AppSettings.Appearance.light) + Text("Dark").tag(AppSettings.Appearance.dark) + } + .pickerStyle(.segmented) + LabeledContent("Accent color") { AccentSwatches(selection: $model.settings.accent) } + Picker("Avatars", selection: $model.settings.avatarStyle) { + ForEach(AvatarStyle.allCases) { Text($0.label).tag($0) } + } + .pickerStyle(.segmented) + Toggle("Animate avatars on hover", isOn: $model.settings.animateAvatars) + Picker("Text size", selection: $model.settings.textSize) { + ForEach(TextSize.allCases) { Text($0.label).tag($0) } + } + .pickerStyle(.segmented) + Picker("Density", selection: $model.settings.density) { + ForEach(Density.allCases) { Text($0.label).tag($0) } + } + .pickerStyle(.segmented) + } + Section("Conversation") { + Picker("Message style", selection: $model.settings.bubbleStyle) { + ForEach(BubbleStyle.allCases) { Text($0.label).tag($0) } + } + .pickerStyle(.segmented) + Toggle("Show timestamps between messages", isOn: $model.settings.showTimestamps) + Picker("Send messages with", selection: $model.settings.sendWithReturn) { + Text("Return").tag(true) + Text("⌘ Return").tag(false) + } + .pickerStyle(.segmented) + Text(model.settings.sendWithReturn ? "Shift-Return adds a new line." : "Return adds a new line.") + .font(.caption).foregroundStyle(.secondary) + } + Section("Sidebar") { + Toggle("Show pinned databases", isOn: $model.settings.showPinnedBots) + Toggle("Group databases by environment", isOn: $model.settings.groupByEnvironment) + Toggle("Show latest finding under each database", isOn: $model.settings.showSidebarPreviews) + Toggle("Reopen the last database at launch", isOn: $model.settings.restoreLastSelection) + } + Section("Menu bar") { + Toggle("Show menu bar icon", isOn: $model.settings.showMenuBarIcon) + Text("With the menu bar icon on, PGBot keeps monitoring after you close the window.").font(.caption).foregroundStyle(.secondary) + } + Section { + HStack { Spacer(); Button("Restore Default Appearance") { model.settings.resetAppearance() } } + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +/// Accent color picker in the style of System Settings. +@MainActor private struct AccentSwatches: View { + @Binding var selection: AccentChoice + var body: some View { + HStack(spacing: 7) { + ForEach(AccentChoice.allCases) { a in + Button { selection = a } label: { + Circle() + .fill(a == .system + ? AnyShapeStyle(AngularGradient(colors: [.red, .orange, .yellow, .green, .blue, .purple, .red], center: .center)) + : AnyShapeStyle(a.color)) + .frame(width: 18, height: 18) + .overlay(Circle().fill(.white).frame(width: 6, height: 6).opacity(selection == a ? 1 : 0)) + .overlay(Circle().strokeBorder(Color.primary.opacity(0.12))) + } + .buttonStyle(.plain) + .help(a.label) + .accessibilityLabel(a.label) + .accessibilityAddTraits(selection == a ? .isSelected : []) + } + } + } +} + +/// Starting values for the Add Database sheet. Monitoring defaults live under Monitoring. +@MainActor private struct NewDatabaseSettings: View { + @Environment(AppModel.self) private var model + var body: some View { + @Bindable var model = model + Form { + Section("Connection") { + Picker("Environment", selection: $model.settings.defaultEnvironment) { + ForEach(DatabaseEnvironment.allCases) { Text($0.label).tag($0) } + } + Picker("SSL mode", selection: $model.settings.defaultSSLMode) { + ForEach(SSLMode.allCases) { Text($0.rawValue).tag($0) } + } + Stepper("Connection timeout: \(model.settings.defaultConnectTimeout)s", + value: $model.settings.defaultConnectTimeout, in: 2...120) + Text("Use “require” or “verify-full” for databases outside this Mac. A pasted connection URL overrides these.") + .font(.caption).foregroundStyle(.secondary) + } + Section("Bot") { + Picker("Avatar shape", selection: $model.settings.defaultAvatarShape) { + Text("Rounded square").tag(AvatarShape.roundedSquare) + Text("Circle").tag(AvatarShape.circle) + } + .pickerStyle(.segmented) + Picker("Avatar color", selection: $model.settings.defaultAvatarColor) { + Text("Random").tag(BotColor?.none) + Divider() + ForEach(BotColor.allCases) { Text($0.label).tag(BotColor?.some($0)) } + } + HStack(spacing: 10) { + Spacer() + ElephantAvatar(color: model.settings.defaultAvatarColor ?? .blue, shape: model.settings.defaultAvatarShape, size: 44) + Spacer() + } + } + Section("Monitoring") { + LabeledContent("Inspection interval, daily report, retention") { + Text("Settings → Monitoring").foregroundStyle(.secondary) + } + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +@MainActor private struct MonitoringSettings: View { + @Environment(AppModel.self) private var model + var body: some View { + @Bindable var model = model + Form { + Toggle("Background monitoring", isOn: $model.settings.backgroundMonitoring) + Picker("Default inspection interval", selection: $model.settings.defaultIntervalSeconds) { + ForEach(MonitoringSchedule.intervalChoices, id: \.1) { Text($0.0).tag($0.1) } + } + Picker("Default daily report", selection: $model.settings.defaultDailyReportHour) { + Text("Off").tag(Int?.none) + ForEach([7, 8, 9, 10], id: \.self) { Text("\($0):00").tag(Int?.some($0)) } + } + Picker("Default data retention", selection: $model.settings.defaultRetentionDays) { + ForEach([7, 30, 90, 365], id: \.self) { Text("\($0) days").tag($0) } + } + Toggle("Launch at login", isOn: $model.settings.launchAtLogin) + Section { + Text("Monitoring is local: it runs while PGBot is open or in the menu bar and this Mac is awake and online. It does not cover time the Mac is asleep or off. Always-on cloud monitoring is planned for Pro.") + .font(.callout).foregroundStyle(.secondary) + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +@MainActor private struct AIProviderSettings: View { + @Environment(AppModel.self) private var model + @State private var key = "" + @State private var saved = false + + var body: some View { + @Bindable var model = model + Form { + Picker("Provider", selection: $model.settings.ai.provider) { + ForEach(AIProviderKind.allCases) { Text($0.label).tag($0) } + } + .onChange(of: model.settings.ai.provider) { _, _ in key = ""; saved = false; model.settings.ai.model = "" } + Picker("Model", selection: $model.settings.ai.model) { + Text("Provider default").tag("") + ForEach(model.settings.ai.provider.suggestedModels, id: \.self) { Text($0).tag($0) } + if !model.settings.ai.model.isEmpty && !model.settings.ai.provider.suggestedModels.contains(model.settings.ai.model) { + Text(model.settings.ai.model).tag(model.settings.ai.model) + } + } + TextField("Custom model id", text: $model.settings.ai.model, prompt: Text("Optional")) + if model.settings.ai.provider.needsBaseURL || model.settings.ai.provider == .ollama { + TextField("Endpoint", text: $model.settings.ai.baseURL, + prompt: Text(model.settings.ai.provider.defaultBaseURL ?? "https://…/v1")) + } + if model.settings.ai.provider.needsKey { + HStack { + SecureField("API key", text: $key, prompt: Text(model.hasAPIKey(model.settings.ai.provider) ? "Saved in Keychain" : "Paste your key")) + Button("Save") { model.saveAPIKey(key, for: model.settings.ai.provider); key = ""; saved = true }.disabled(key.isEmpty) + if model.hasAPIKey(model.settings.ai.provider) { + Button("Remove", role: .destructive) { model.saveAPIKey("", for: model.settings.ai.provider); saved = false } + } + } + if saved { Label("Saved to your Keychain", systemImage: "checkmark").foregroundStyle(.green).font(.caption) } + } + Section("Privacy") { + Text("The engine sends only PII-free findings and your question — never credentials, connection strings, or table contents. Local models (Ollama) keep everything on this Mac.") + .font(.callout).foregroundStyle(.secondary) + if !model.settings.aiConsents.isEmpty { + Button("Revoke data-sharing consent (\(model.settings.aiConsents.count))") { model.settings.aiConsents = [] } + } + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +@MainActor private struct NotificationSettings: View { + @Environment(AppModel.self) private var model + @State private var testResult: String? + @State private var permission: SystemNotifications.Permission = .unknown + + var body: some View { + @Bindable var model = model + Form { + Section { + Toggle("Allow notifications", isOn: $model.settings.notificationsEnabled) + .onChange(of: model.settings.notificationsEnabled) { _, on in + if on { model.requestNotificationPermission() } + Task { permission = await SystemNotifications.permission() } + } + permissionRow + } footer: { + Text("PGBot notifies you when findings appear, get worse, or are resolved — once per change, never repeated for something you've already seen.") + .font(.caption).foregroundStyle(.secondary) + } + + Section("How") { + Toggle("Show macOS banners", isOn: $model.settings.systemBanners) + Toggle("Play sound", isOn: $model.settings.notificationSounds) + .disabled(!model.settings.systemBanners) + Toggle("Show details in banners", isOn: $model.settings.showPreviews) + .disabled(!model.settings.systemBanners) + Text(model.settings.showPreviews ? "Banners name the finding, e.g. “Three unused indexes occupy 4.2 GB”." + : "Banners only say which database needs a look — useful when sharing your screen.") + .font(.caption).foregroundStyle(.secondary) + Toggle("Badge the Dock icon with unread count", isOn: $model.settings.dockBadge) + HStack { + Button("Send Test Notification") { testResult = model.sendTestNotification() ?? "Sent — look at the top-right corner of your screen." } + if let testResult { Text(testResult).font(.caption).foregroundStyle(.secondary) } + } + } + .disabled(!model.settings.notificationsEnabled) + + Section("What") { + Picker("Notify me about", selection: $model.settings.minimumSeverity) { + Text("Critical only").tag(Severity.critical) + Text("Warnings and critical").tag(Severity.warn) + Text("Everything").tag(Severity.info) + } + ForEach(NotificationCategory.allCases, id: \.self) { c in + Toggle(isOn: Binding(get: { !model.settings.disabledCategories.contains(c) }, + set: { on in if on { model.settings.disabledCategories.remove(c) } else { model.settings.disabledCategories.insert(c) } })) { + VStack(alignment: .leading, spacing: 2) { + Label(c.label, systemImage: c.symbol) + Text(c.detail).font(.caption).foregroundStyle(.secondary) + } + } + } + } + .disabled(!model.settings.notificationsEnabled) + + Section("When") { + Toggle("Quiet hours", isOn: $model.settings.quietHours.enabled) + if model.settings.quietHours.enabled { + Picker("From", selection: $model.settings.quietHours.startHour) { ForEach(0..<24, id: \.self) { Text(hourLabel($0)).tag($0) } } + Picker("Until", selection: $model.settings.quietHours.endHour) { ForEach(0..<24, id: \.self) { Text(hourLabel($0)).tag($0) } } + Toggle("Critical alerts still come through", isOn: $model.settings.criticalBreaksQuietHours) + } + Text("Monitoring runs while this Mac is awake. Nothing is checked — or notified — while it sleeps.") + .font(.caption).foregroundStyle(.secondary) + } + .disabled(!model.settings.notificationsEnabled) + + Section("Per database") { + if model.bots.isEmpty { + Text("Add a database to choose its notifications.").foregroundStyle(.secondary) + } + ForEach(model.bots) { bot in + Picker(selection: level(bot)) { + Text("Everything").tag(Level.everything) + Text("Warnings and critical").tag(Level.warnings) + Text("Critical only").tag(Level.critical) + Divider() + Text("Off").tag(Level.off) + } label: { + HStack(spacing: 10) { + BotAvatarView(bot: bot, size: 24) + Text(bot.displayName) + } + } + } + if !model.bots.isEmpty { + Text("A database's level applies together with “Notify me about” above — the stricter of the two wins.") + .font(.caption).foregroundStyle(.secondary) + } + } + .disabled(!model.settings.notificationsEnabled) + } + .formStyle(.grouped).scrollContentBackground(.hidden) + .task { permission = await SystemNotifications.permission() } + } + + @ViewBuilder private var permissionRow: some View { + if !SystemNotifications.available { + Label("macOS notifications need the installed PGBot.app; this build shows them in PGBot only.", systemImage: "info.circle") + .font(.callout).foregroundStyle(.secondary) + } else { + switch permission { + case .allowed: + Label("macOS: allowed", systemImage: "checkmark.circle.fill").foregroundStyle(Palette.healthy) + case .denied: + HStack { + Label("macOS: blocked in System Settings", systemImage: "xmark.octagon.fill").foregroundStyle(.red) + Spacer() + Button("Open System Settings") { SystemNotifications.openSystemSettings() } + } + case .notAsked: + HStack { + Label("macOS hasn't asked yet", systemImage: "questionmark.circle").foregroundStyle(.secondary) + Spacer() + Button("Ask Now") { + model.requestNotificationPermission() + Task { try? await Task.sleep(for: .seconds(1)); permission = await SystemNotifications.permission() } + } + } + case .unknown: + EmptyView() + } + } + } + + enum Level: Hashable { case everything, warnings, critical, off } + + private func level(_ bot: DatabaseBot) -> Binding { + Binding( + get: { + guard let b = model.bot(bot.id) else { return .warnings } + if b.muted { return .off } + switch b.schedule.notifyMinimum { case .info: return .everything; case .warn: return .warnings; case .critical: return .critical } + }, + set: { new in + model.mutate(bot.id) { b in + b.muted = new == .off + switch new { + case .everything: b.schedule.notifyMinimum = .info + case .warnings: b.schedule.notifyMinimum = .warn + case .critical: b.schedule.notifyMinimum = .critical + case .off: break + } + } + }) + } + + private func hourLabel(_ h: Int) -> String { + Calendar.current.date(bySettingHour: h, minute: 0, second: 0, of: Date())!.formatted(date: .omitted, time: .shortened) + } +} + +extension NotificationCategory { + var symbol: String { + switch self { + case .criticalFinding: "exclamationmark.octagon" + case .warning: "exclamationmark.triangle" + case .scoreChange: "gauge.with.dots.needle.33percent" + case .regression: "tortoise" + case .connectivity: "bolt.horizontal.circle" + case .resolved: "checkmark.circle" + case .scheduledReport: "sun.horizon" + } + } + var detail: String { + switch self { + case .criticalFinding: "Something needs action now, like wraparound risk or a full disk." + case .warning: "A new warning, like unused indexes or autovacuum falling behind." + case .scoreChange: "The health score dropped by 10 points or more." + case .regression: "A query or workload got noticeably slower." + case .connectivity: "PGBot couldn't reach the database — and when it's back." + case .resolved: "A finding you were told about has gone away." + case .scheduledReport: "The morning health report for each database." + } + } +} + +@MainActor private struct IntegrationSettings: View { + var body: some View { + Form { + ForEach(["Slack", "Discord", "Email", "GitHub", "Webhooks", "Prometheus", "OpenTelemetry"], id: \.self) { name in + LabeledContent(name) { Text("Coming soon").foregroundStyle(.tertiary) } + } + Text("Integrations deliver the same deduplicated notifications to your team's channels. Prometheus is already available from the CLI: `pgbot inspect --format=prometheus`.") + .font(.caption).foregroundStyle(.secondary) + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +@MainActor private struct PrivacySettings: View { + @Environment(AppModel.self) private var model + var body: some View { + @Bindable var model = model + Form { + Section("Local data") { + LabeledContent("Conversations & history", value: "~/Library/Application Support/PGBot") + LabeledContent("Passwords & API keys", value: "macOS Keychain (this Mac only)") + Button("Show in Finder") { + let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("PGBot") + NSWorkspace.shared.activateFileViewerSelecting([url]) + } + } + Section { + Toggle("Share anonymous usage statistics", isOn: $model.settings.telemetryOptIn) + Text("Off by default. Database contents, names, queries and findings are never collected.").font(.caption).foregroundStyle(.secondary) + LabeledContent("Cloud sync", value: "Off — everything stays on this Mac") + } + Section { + Button("Delete All Local Data…", role: .destructive) { + let a = NSAlert() + a.messageText = "Delete all local PGBot data?" + a.informativeText = "Removes every database bot, conversation, history, setting, saved password and API key from this Mac. Your databases are not touched." + a.addButton(withTitle: "Delete"); a.addButton(withTitle: "Cancel") + if a.runModal() == .alertFirstButtonReturn { model.deleteAllLocalData() } + } + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} + +@MainActor private struct AboutSettings: View { + @Environment(AppModel.self) private var model + var body: some View { + @Bindable var model = model + Form { + HStack(spacing: Space.m) { + PGBotLogo(size: 56) + VStack(alignment: .leading) { + Text("PGBot").font(.title2.weight(.semibold)) + Text("Every PostgreSQL database deserves its own intelligent assistant.").foregroundStyle(.secondary) + } + } + LabeledContent("App version", value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "development") + LabeledContent("Engine version", value: model.engineVersion ?? (model.engineProblem?.title ?? "…")) + TextField("Engine path override", text: $model.settings.enginePathOverride, prompt: Text("Bundled engine")) + Section { + Link("Documentation", destination: URL(string: "https://pgbot.dev")!) + Link("GitHub repository", destination: URL(string: "https://github.com/pgrundev/pgbot")!) + Link("Report an issue", destination: URL(string: "https://github.com/pgrundev/pgbot/issues/new")!) + Link("License (Apache-2.0)", destination: URL(string: "https://github.com/pgrundev/pgbot/blob/main/LICENSE")!) + } + } + .formStyle(.grouped).scrollContentBackground(.hidden) + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Settings/DatabaseSettingsView.swift b/desktop/macos/Sources/PGBot/Features/Settings/DatabaseSettingsView.swift new file mode 100644 index 0000000..3dcb4fa --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Settings/DatabaseSettingsView.swift @@ -0,0 +1,180 @@ +import PGBotKit +import SwiftUI + +/// Per-bot settings. Edits a draft and saves on "Done", so Cancel really cancels. +@MainActor struct DatabaseSettingsView: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + let botID: UUID + @State private var draft: DatabaseBot? + @State private var newPassword = "" + @State private var testing = false + @State private var testResult: String? + + var body: some View { + VStack(spacing: 0) { + if let binding = Binding($draft) { + TabView { + general(binding).tabItem { Text("General") } + connection(binding).tabItem { Text("Connection") } + monitoring(binding).tabItem { Text("Monitoring") } + notifications(binding).tabItem { Text("Notifications") } + ai.tabItem { Text("AI") } + advanced(binding).tabItem { Text("Advanced") } + } + .padding(Space.l) + } + Divider() + HStack { + Button("Cancel", role: .cancel) { dismiss() }.keyboardShortcut(.cancelAction) + Spacer() + Button("Done") { save() }.keyboardShortcut(.defaultAction).buttonStyle(.borderedProminent) + } + .padding(Space.l) + } + .frame(width: 600, height: 560) + .onAppear { draft = model.bot(botID) } + } + + private func save() { + guard let d = draft else { return } + if !newPassword.isEmpty { model.setPassword(newPassword, for: d) } + model.update(d) + dismiss() + } + + private func general(_ b: Binding) -> some View { + Form { + LabeledContent("Avatar") { ElephantAvatar(color: b.wrappedValue.avatar.color, shape: b.wrappedValue.avatar.shape, size: 48) } + TextField("Display name", text: b.displayName) + TextField("Description", text: b.description) + LabeledContent("Color") { ColorSwatches(selection: b.avatar.color, shape: b.wrappedValue.avatar.shape) } + Picker("Shape", selection: b.avatar.shape) { + Text("Rounded square").tag(AvatarShape.roundedSquare); Text("Circle").tag(AvatarShape.circle) + }.pickerStyle(.segmented) + Picker("Environment", selection: b.environment) { ForEach(DatabaseEnvironment.allCases) { Text($0.label).tag($0) } } + TextField("Custom group", text: Binding(get: { b.wrappedValue.customGroup ?? "" }, + set: { b.wrappedValue.customGroup = $0.isEmpty ? nil : $0 }), prompt: Text("Uses the environment")) + Toggle("Pinned", isOn: b.pinned) + } + .formStyle(.grouped) + } + + private func connection(_ b: Binding) -> some View { + Form { + TextField("Host", text: b.connection.host) + TextField("Port", value: b.connection.port, format: .number.grouping(.never)) + TextField("Database", text: b.connection.database) + TextField("Username", text: b.connection.username) + SecureField("New password", text: $newPassword, prompt: Text("Unchanged (stored in Keychain)")) + Picker("SSL mode", selection: b.connection.sslMode) { ForEach(SSLMode.allCases) { Text($0.rawValue).tag($0) } } + Stepper("Connection timeout: \(b.wrappedValue.connection.connectTimeoutSeconds)s", value: b.connection.connectTimeoutSeconds, in: 2...120) + Section { + HStack { + Button("Test Connection") { Task { await test(b.wrappedValue) } }.disabled(testing || b.wrappedValue.isDemo) + if testing { ProgressView().controlSize(.small) } + if let r = testResult { Text(r).font(.callout).foregroundStyle(.secondary) } + } + if let ctx = model.latest[botID]?.context { + LabeledContent("Monitoring permissions", value: ctx.server.hasPgMonitor == true ? "pg_monitor granted" : "pg_monitor missing") + LabeledContent("pg_stat_statements", value: ctx.queries?.isAvailable == true ? "Enabled" : "Not available") + } + } + } + .formStyle(.grouped) + } + + private func monitoring(_ b: Binding) -> some View { + Form { + Toggle("Monitor this database", isOn: b.schedule.enabled) + Picker("Inspect", selection: b.schedule.intervalSeconds) { + ForEach(MonitoringSchedule.intervalChoices, id: \.1) { Text($0.0).tag($0.1) } + } + Picker("Daily report", selection: b.schedule.dailyReportHour) { + Text("Off").tag(Int?.none) + ForEach([6, 7, 8, 9, 10, 12, 17], id: \.self) { h in + Text(Calendar.current.date(bySettingHour: h, minute: 0, second: 0, of: Date())!.formatted(date: .omitted, time: .shortened)).tag(Int?.some(h)) + } + } + Picker("Keep local history", selection: b.schedule.retentionDays) { + ForEach([7, 30, 90, 365], id: \.self) { Text("\($0) days").tag($0) } + } + Section("Ignored findings") { + if b.wrappedValue.schedule.ignoredFindingKeys.isEmpty { + Text("None. Use “Ignore” on a finding to hide it for this database.").foregroundStyle(.secondary) + } + ForEach(Array(b.wrappedValue.schedule.ignoredFindingKeys).sorted(), id: \.self) { k in + HStack { + Text(k).font(.system(.callout, design: .monospaced)) + Spacer() + Button("Restore") { b.wrappedValue.schedule.ignoredFindingKeys.remove(k) }.buttonStyle(.link) + } + } + } + Text("Local monitoring runs while PGBot is open (or in the menu bar) and this Mac is awake. It isn't 24/7 coverage.") + .font(.caption).foregroundStyle(.secondary) + } + .formStyle(.grouped) + } + + private func notifications(_ b: Binding) -> some View { + Form { + Toggle("Mute this database", isOn: b.muted) + Picker("Notify for", selection: b.schedule.notifyMinimum) { + Text("Critical findings only").tag(Severity.critical) + Text("Warnings and critical").tag(Severity.warn) + Text("Everything").tag(Severity.info) + } + Toggle("Recovery notifications", isOn: b.schedule.notifyResolved) + Text("Quiet hours, sounds and categories are global: Settings → Notifications.").font(.caption).foregroundStyle(.secondary) + } + .formStyle(.grouped) + } + + private var ai: some View { + Form { + LabeledContent("Provider", value: model.settings.ai.provider.label) + LabeledContent("Model", value: model.settings.ai.model.isEmpty ? "Provider default" : model.settings.ai.model) + Text("AI answers explain PGBot's deterministic findings; the model never connects to the database. Configure providers and keys in Settings → AI providers.") + .font(.callout).foregroundStyle(.secondary) + Button("Open AI settings…") { dismiss(); openAppSettings(tab: "ai") } + } + .formStyle(.grouped) + } + + private func advanced(_ b: Binding) -> some View { + Form { + Section { + Button("Export Inspection Report…") { model.exportInspection(botID) }.disabled(model.latest[botID] == nil) + Button("Export Conversation History…") { model.exportConversation(botID) } + Button("Clear Local History", role: .destructive) { model.clearConversation(botID) } + } + Section { + Button("Remove Database…", role: .destructive) { + let alert = NSAlert() + alert.messageText = "Remove “\(b.wrappedValue.displayName)”?" + alert.informativeText = "This deletes its conversation, history and saved password from this Mac. The database itself is not touched." + alert.addButton(withTitle: "Remove"); alert.addButton(withTitle: "Cancel") + if alert.runModal() == .alertFirstButtonReturn { dismiss(); model.remove(botID) } + } + } + Text("Statement timeouts and per-database engine options use the engine's defaults (read-only session, bounded statement time).") + .font(.caption).foregroundStyle(.secondary) + } + .formStyle(.grouped) + } + + private func test(_ bot: DatabaseBot) async { + guard let engine = model.engine else { testResult = model.engineProblem?.title; return } + testing = true; testResult = nil + defer { testing = false } + let pw = newPassword.isEmpty ? model.password(for: bot) : newPassword + do { + let ctx = try await engine.inspect(EngineTarget(connection: bot.connection, password: pw)) + testResult = "Connected — \(ctx.server.displayVersion)" + } catch { + let e = error as? EngineError ?? .failed(error.localizedDescription) + testResult = "\(e.title). \(e.hint)" + } + } +} diff --git a/desktop/macos/Sources/PGBot/Features/Sidebar/MainView.swift b/desktop/macos/Sources/PGBot/Features/Sidebar/MainView.swift new file mode 100644 index 0000000..827f3bc --- /dev/null +++ b/desktop/macos/Sources/PGBot/Features/Sidebar/MainView.swift @@ -0,0 +1,423 @@ +import PGBotKit +import SwiftUI + +/// Two surfaces, no toolbar: a soft gray sidebar and a white conversation +/// canvas. The window's title bar is hidden; the traffic lights sit in the sidebar. +@MainActor struct MainView: View { + @Environment(AppModel.self) private var model + @AppStorage("sidebarWidth") private var sidebarWidth: Double = 290 + @State private var dragOrigin: Double? + + var body: some View { + @Bindable var model = model + HStack(spacing: 0) { + SidebarView() + .frame(width: sidebarWidth) + .background(Palette.sidebar) + resizeHandle + detail + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Palette.canvas) + } + .ignoresSafeArea() + .sheet(isPresented: $model.showingAddDatabase) { AddDatabaseSheet() } + .sheet(item: $model.settingsForBot) { bot in DatabaseSettingsView(botID: bot.id) } + .sheet(item: $model.pendingConsent) { c in AIConsentSheet(consent: c) } + .sheet(isPresented: Binding(get: { model.explainSQLDraft != nil }, set: { if !$0 { model.explainSQLDraft = nil } })) { + ExplainSQLSheet() + } + .sheet(isPresented: $model.showingSearch) { SearchPalette() } + } + + @ViewBuilder private var detail: some View { + if model.bots.isEmpty { + ZStack(alignment: .top) { + OnboardingView() + StatusNotes().padding(.top, 14) + } + } else if let bot = model.selectedBot { + BotDetailView(bot: bot).id(bot.id) + } else { + ContentUnavailableView("Select a database", systemImage: "cylinder.split.1x2", + description: Text("Choose a database bot in the sidebar.")) + } + } + + /// An invisible edge you can drag to resize the sidebar (no divider line: + /// the two surface colors already separate the columns). + private var resizeHandle: some View { + Color.clear.frame(width: 0) + .overlay { + Color.clear.frame(width: 9).contentShape(Rectangle()) + .onHover { inside in if inside { NSCursor.resizeLeftRight.push() } else { NSCursor.pop() } } + .gesture(DragGesture(minimumDistance: 1, coordinateSpace: .global) + .onChanged { v in + if dragOrigin == nil { dragOrigin = sidebarWidth } + sidebarWidth = min(420, max(240, (dragOrigin ?? sidebarWidth) + v.translation.width)) + } + .onEnded { _ in dragOrigin = nil }) + } + } +} + +/// Small floating notes for rare app-wide states (engine missing, offline, paused). +/// Demo mode is marked by DEMO badges on the title pill and every row instead. +@MainActor struct StatusNotes: View { + @Environment(AppModel.self) private var model + var body: some View { + VStack(spacing: 6) { + if let p = model.engineProblem { note("exclamationmark.triangle.fill", .orange, p.title, help: p.hint) { EmptyView() } } + if model.isOffline { note("wifi.slash", .secondary, "Offline — monitoring resumes when you're back") { EmptyView() } } + if model.monitoringPaused && !model.bots.isEmpty && !model.demoMode { + note("pause.circle.fill", .secondary, "Monitoring paused") { Button("Resume") { model.setMonitoringPaused(false) }.buttonStyle(.link) } + } + } + .font(Typo.small) + } + + private func note(_ symbol: String, _ color: Color, _ text: String, help: String? = nil, @ViewBuilder action: () -> A) -> some View { + HStack(spacing: 6) { + Image(systemName: symbol).foregroundStyle(color) + Text(text).foregroundStyle(.secondary) + action() + } + .floatingPill(height: 28) + .help(help ?? text) + } +} + +// MARK: - Sidebar + +@MainActor struct SidebarView: View { + @Environment(AppModel.self) private var model + + var body: some View { + VStack(spacing: 0) { + // Same line as the traffic lights. + HStack(spacing: 8) { + Spacer() + CircleButton(symbol: "magnifyingglass", help: "Search (⌘K)") { model.showingSearch = true } + CircleButton(symbol: "plus", help: "Add database (⌘N)") { model.showingAddDatabase = true } + } + .padding(.horizontal, 12) + .frame(height: 48) + + ScrollView { + VStack(alignment: .leading, spacing: 2) { + if model.settings.showPinnedBots && !pinned.isEmpty { + PinnedStrip(bots: pinned).padding(.top, 18).padding(.horizontal, 2).padding(.bottom, 10) + } + if model.settings.groupByEnvironment { + ForEach(model.groups, id: \.name) { group in GroupSection(name: group.name, bots: group.bots) } + } else { + ForEach(model.bots.sorted { $0.sortOrder < $1.sortOrder }) { bot in row(bot) } + .padding(.top, 4) + } + } + .padding(.horizontal, 10) + .padding(.bottom, 12) + } + .scrollIndicators(.never) + + SidebarFooter() + } + } + + private var pinned: [DatabaseBot] { model.bots.filter(\.pinned).sorted { $0.sortOrder < $1.sortOrder } } + + private func row(_ bot: DatabaseBot) -> some View { + BotRow(bot: bot, selected: model.selection == bot.id, inspecting: model.inspecting.contains(bot.id), + compact: model.settings.density == .compact, showsPreview: model.settings.showSidebarPreviews) + .onTapGesture { model.selection = bot.id; model.route = .chat } + .contextMenu { BotContextMenu(bot: bot) } + } +} + +@MainActor struct GroupSection: View { + @Environment(AppModel.self) private var model + let name: String + let bots: [DatabaseBot] + + var body: some View { + let collapsed = model.settings.collapsedGroups.contains(name) + Button { + withAnimation(.snappy(duration: 0.2)) { + if collapsed { model.settings.collapsedGroups.remove(name) } else { model.settings.collapsedGroups.insert(name) } + } + } label: { + HStack { + Text(name) + Spacer() + if collapsed { Text("\(bots.count)").monospacedDigit() } + } + .font(Typo.small) + .foregroundStyle(.secondary) + .padding(.horizontal, 10) + .padding(.top, 14).padding(.bottom, 4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel("\(name), \(collapsed ? "collapsed" : "expanded")") + + if !collapsed { + ForEach(bots) { bot in + BotRow(bot: bot, selected: model.selection == bot.id, inspecting: model.inspecting.contains(bot.id), + compact: model.settings.density == .compact, showsPreview: model.settings.showSidebarPreviews) + .onTapGesture { model.selection = bot.id; model.route = .chat } + .contextMenu { BotContextMenu(bot: bot) } + } + } + } +} + +/// Pinned bots: a 3-column grid of tiles (58pt avatar over a 13pt label). +@MainActor struct PinnedStrip: View { + @Environment(AppModel.self) private var model + let bots: [DatabaseBot] + + var body: some View { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 3), spacing: 6) { + ForEach(bots) { tile($0) } + } + } + + private func tile(_ bot: DatabaseBot) -> some View { + let selected = model.selection == bot.id + return Button { model.selection = bot.id; model.route = .chat } label: { + VStack(spacing: 8) { + BotAvatarView(bot: bot, size: 58, showsStatus: true) + .overlay(alignment: .topTrailing) { + if bot.unreadCount > 0 { + Circle().fill(Theme.accent).frame(width: 12, height: 12) + .overlay(Circle().strokeBorder(selected ? Palette.selection : Palette.sidebar, lineWidth: 2.5)) + .offset(x: 2, y: -2) + } + } + Text(bot.displayName) + .font(.sys(size: 13)) + .foregroundStyle(selected ? Color.primary : Color.primary.opacity(0.85)) + .lineLimit(1).truncationMode(.tail) + } + .padding(.top, 10).padding(.horizontal, 4).padding(.bottom, 12) + .frame(maxWidth: .infinity) + .background(selected ? Palette.selection : .clear, in: RoundedRectangle(cornerRadius: 14, style: .continuous)) + .contentShape(RoundedRectangle(cornerRadius: 14)) + } + .buttonStyle(.plain) + .contextMenu { BotContextMenu(bot: bot) } + .accessibilityLabel("\(bot.displayName), \(bot.status.label)\(bot.unreadCount > 0 ? ", unread" : "")") + } +} + +@MainActor struct BotRow: View { + let bot: DatabaseBot + var selected = false + var inspecting = false + var compact = false + var showsPreview = true + @State private var hovering = false + + var body: some View { + HStack(spacing: 12) { + BotAvatarView(bot: bot, size: compact || !showsPreview ? 28 : 36, showsStatus: true) + VStack(alignment: .leading, spacing: 1) { + HStack(spacing: 5) { + Text(bot.displayName) + .font(.sys(size: 15, weight: bot.unreadCount > 0 ? .semibold : .regular)) + .lineLimit(1) + if bot.isDemo { DemoBadge() } + if bot.muted { Image(systemName: "bell.slash").font(.sys(size: 10)).foregroundStyle(.tertiary) } + } + if showsPreview { + Text(subtitle).font(.sys(size: 13)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.tail) + } + } + Spacer(minLength: 4) + if inspecting { ProgressView().controlSize(.mini) } + else if bot.unreadCount > 0 { Circle().fill(Theme.accent).frame(width: 8, height: 8) } + } + .padding(compact ? 5 : 8) + .background(RoundedRectangle(cornerRadius: 12, style: .continuous) + .fill(selected ? Palette.selection : (hovering ? Palette.hover : .clear))) + .contentShape(RoundedRectangle(cornerRadius: 12)) + .onHover { hovering = $0 } + .accessibilityElement(children: .combine) + .accessibilityAddTraits(selected ? [.isSelected, .isButton] : .isButton) + } + + private var subtitle: String { + if inspecting { return "Inspecting…" } + if !bot.schedule.enabled { return "Monitoring paused" } + return bot.lastSummary ?? "Not inspected yet" + } +} + +@MainActor struct BotContextMenu: View { + @Environment(AppModel.self) private var model + let bot: DatabaseBot + var body: some View { + Button("Run Inspection") { Task { await model.inspect(bot.id, reason: .manual) } }.disabled(bot.isDemo) + Divider() + Button(bot.pinned ? "Unpin" : "Pin to Top") { model.mutate(bot.id) { $0.pinned.toggle() } } + let ids = model.groups.first { $0.bots.contains { $0.id == bot.id } }?.bots.map(\.id) ?? [] + if let i = ids.firstIndex(of: bot.id) { + Button("Move Up") { model.move(from: IndexSet(integer: i), to: i - 1, within: ids) }.disabled(i == 0) + Button("Move Down") { model.move(from: IndexSet(integer: i), to: i + 2, within: ids) }.disabled(i == ids.count - 1) + } + Menu("Color") { + ForEach(BotColor.allCases) { c in + Button { model.mutate(bot.id) { $0.avatar.color = c } } label: { Label(c.label, systemImage: bot.avatar.color == c ? "checkmark" : "circle.fill") } + } + } + Menu("Move to Group") { + ForEach(DatabaseEnvironment.allCases.filter { $0 != .custom }) { e in + Button(e.label) { model.mutate(bot.id) { $0.environment = e; $0.customGroup = nil } } + } + } + Button(bot.muted ? "Unmute Notifications" : "Mute Notifications") { model.mutate(bot.id) { $0.muted.toggle() } } + Button(bot.schedule.enabled ? "Pause Monitoring" : "Resume Monitoring") { + model.mutate(bot.id) { $0.schedule.enabled.toggle(); $0.status = $0.schedule.enabled ? .unknown : .paused } + } + Divider() + Button("Settings…") { model.settingsForBot = bot } + Divider() + Button("Remove Database…", role: .destructive) { confirmRemove(bot) } + } + + private func confirmRemove(_ bot: DatabaseBot) { + let alert = NSAlert() + alert.messageText = "Remove “\(bot.displayName)”?" + alert.informativeText = "This deletes its conversation, history and saved password from this Mac. The database itself is not touched." + alert.addButton(withTitle: "Remove") + alert.addButton(withTitle: "Cancel") + alert.buttons.first?.hasDestructiveAction = true + if alert.runModal() == .alertFirstButtonReturn { model.remove(bot.id) } + } +} + +@MainActor struct SidebarFooter: View { + @Environment(AppModel.self) private var model + @State private var hoveringAdd = false + + var body: some View { + @Bindable var model = model + HStack(spacing: 8) { + Button { model.showingAddDatabase = true } label: { + HStack(spacing: 10) { + Image(systemName: "plus").font(.system(size: 13, weight: .medium)) + .frame(width: 30, height: 30) + .background(Palette.control, in: Circle()) + Text("Add database").font(.sys(size: 15)) + } + .padding(.vertical, 4).padding(.horizontal, 6).padding(.trailing, 6) + .background(hoveringAdd ? Palette.hover : .clear, in: Capsule()) + .contentShape(Capsule()) + .onHover { hoveringAdd = $0 } + } + .buttonStyle(.plain) + + Spacer() + CircleButton(symbol: "bell", help: "Notifications", size: 30, badge: model.unreadNotifications > 0) { + model.showingNotifications.toggle() + } + .popover(isPresented: $model.showingNotifications, arrowEdge: .top) { NotificationCenterView() } + Menu { + if let s = model.session { + Text(s.user.name) + if let e = s.user.email { Text(e) } + Divider() + } + Button("Settings…") { openAppSettings() } + Button(model.monitoringPaused ? "Resume Monitoring" : "Pause Monitoring") { model.setMonitoringPaused(!model.monitoringPaused) } + Button(model.demoMode ? "Exit Demo Mode" : "Explore Demo Mode") { model.setDemoMode(!model.demoMode) } + Divider() + Button("Switch Account…") { Task { await model.signOut() } } + Button("Sign Out") { Task { await model.signOut() } } + } label: { + ProfileAvatar(name: model.session?.user.name ?? "?", size: 30) + } + .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize() + .help(model.session?.user.name ?? "Account") + } + .padding(.horizontal, 10).padding(.vertical, 12) + } +} + +@MainActor struct ProfileAvatar: View { + let name: String + var size: CGFloat = 26 + var body: some View { + Text(String(name.split(separator: " ").compactMap(\.first).prefix(2)).uppercased()) + .font(.sys(size: size * 0.38, weight: .semibold)) + .foregroundStyle(.white) + .frame(width: size, height: size) + .background(Circle().fill(LinearGradient(colors: [Color(red: 0.45, green: 0.6, blue: 0.98), Color(red: 0.3, green: 0.45, blue: 0.9)], + startPoint: .top, endPoint: .bottom))) + } +} + +/// ⌘K: jump to any database or into a past message. +@MainActor struct SearchPalette: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + @State private var query = "" + @FocusState private var focused: Bool + + var body: some View { + VStack(spacing: 0) { + HStack(spacing: 10) { + Image(systemName: "magnifyingglass").foregroundStyle(.secondary) + TextField("Search databases and conversations", text: $query) + .textFieldStyle(.plain).font(.sys(size: 17)).focused($focused) + .onSubmit { if let first = results.first { go(first.bot, first.message) } } + } + .padding(18) + Divider().opacity(0.5) + ScrollView { + LazyVStack(spacing: 2) { + ForEach(results, id: \.key) { r in + Button { go(r.bot, r.message) } label: { + HStack(spacing: 12) { + BotAvatarView(bot: r.bot, size: 30) + VStack(alignment: .leading, spacing: 1) { + Text(r.bot.displayName).font(.sys(size: 14)) + Text(r.message.map { Format.sqlPreview($0.plainText, limit: 90) } ?? r.bot.connection.safeSummary) + .font(Typo.small).foregroundStyle(.secondary).lineLimit(1) + } + Spacer() + } + .padding(.horizontal, 10).padding(.vertical, 7) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .hoverHighlight(cornerRadius: 10) + } + } + .padding(8) + } + } + .frame(width: 580, height: 420) + .background(Palette.canvas) + .onAppear { focused = true } + .onExitCommand { dismiss() } + } + + struct Result { let key: String; let bot: DatabaseBot; let message: ChatMessage? } + + private var results: [Result] { + let q = query.trimmingCharacters(in: .whitespaces) + let bots = model.bots.filter { q.isEmpty || $0.displayName.localizedCaseInsensitiveContains(q) || $0.connection.host.localizedCaseInsensitiveContains(q) } + .map { Result(key: $0.id.uuidString, bot: $0, message: nil) } + guard q.count >= 2 else { return bots } + let msgs = model.bots.flatMap { b in + model.messages(for: b.id).filter { $0.plainText.localizedCaseInsensitiveContains(q) }.suffix(5) + .map { Result(key: $0.id.uuidString, bot: b, message: $0) } + } + return bots + msgs + } + + private func go(_ bot: DatabaseBot, _ m: ChatMessage?) { + model.selection = bot.id; model.route = .chat; model.scrollTarget = m?.id + dismiss() + } +} diff --git a/desktop/macos/scripts/build-app.sh b/desktop/macos/scripts/build-app.sh new file mode 100755 index 0000000..2da56c5 --- /dev/null +++ b/desktop/macos/scripts/build-app.sh @@ -0,0 +1,87 @@ +#!/usr/bin/env bash +# Builds PGBot.app: the SwiftUI app plus the pgbot Go engine, bundled together. +# +# desktop/macos/scripts/build-app.sh # release build → desktop/macos/build/PGBot.app +# CONFIG=debug desktop/macos/scripts/build-app.sh +# PGBOT_AUTH_BROKER_URL=https://auth.pgbot.dev desktop/macos/scripts/build-app.sh +# +# The engine is built from this repository (same flags as the Makefile) for +# arm64 and amd64 and merged with lipo, so the bundle runs on Apple silicon and +# Intel. The Swift app is built universal when the toolchain supports it (full +# Xcode); Command Line Tools build the host architecture only. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")/.." && pwd)" +REPO="$(cd "$HERE/../.." && pwd)" +CONFIG="${CONFIG:-release}" +OUT="$HERE/build" +APP="$OUT/PGBot.app" +VERSION="${VERSION:-$(git -C "$REPO" describe --tags --always 2>/dev/null | sed 's/^v//' || echo dev)}" +SHORT_VERSION="$(echo "$VERSION" | sed -E 's/^([0-9]+\.[0-9]+\.[0-9]+).*/\1/')" +[[ "$SHORT_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || SHORT_VERSION="0.0.0" + +echo "→ Building engine $VERSION (arm64 + amd64)" +ENGINE_TMP="$(mktemp -d)" +trap 'rm -rf "$ENGINE_TMP"' EXIT +for arch in arm64 amd64; do + (cd "$REPO" && CGO_ENABLED=0 GOOS=darwin GOARCH=$arch go build -trimpath \ + -ldflags "-s -w -X main.version=$VERSION" -o "$ENGINE_TMP/pgbot-$arch" ./cmd/pgbot) +done +lipo -create -output "$ENGINE_TMP/pgbot" "$ENGINE_TMP/pgbot-arm64" "$ENGINE_TMP/pgbot-amd64" + +echo "→ Building app ($CONFIG)" +cd "$HERE" +if swift build -c "$CONFIG" --product PGBot --arch arm64 --arch x86_64 >/dev/null 2>&1; then + BIN_DIR="$(swift build -c "$CONFIG" --product PGBot --arch arm64 --arch x86_64 --show-bin-path)" +else + echo " (universal Swift build unavailable with this toolchain; building $(uname -m) only)" + if ! LOG="$(swift build -c "$CONFIG" --product PGBot 2>&1)"; then + echo "$LOG" | grep -E "error:" | grep -v "xcrun: error" >&2; exit 1 + fi + BIN_DIR="$(swift build -c "$CONFIG" --product PGBot --show-bin-path)" +fi + +echo "→ Assembling $APP" +rm -rf "$APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/engine" +cp "$BIN_DIR/PGBot" "$APP/Contents/MacOS/PGBot" +cp "$ENGINE_TMP/pgbot" "$APP/Contents/Resources/engine/pgbot" +chmod 755 "$APP/Contents/Resources/engine/pgbot" +cp "$REPO/internal/monitor/assets/PgBot.icns" "$APP/Contents/Resources/AppIcon.icns" + +cat > "$APP/Contents/Info.plist" < + + + + CFBundleIdentifierdev.pgbot.desktop + CFBundleNamePGBot + CFBundleDisplayNamePGBot + CFBundleExecutablePGBot + CFBundleIconFileAppIcon + CFBundlePackageTypeAPPL + CFBundleShortVersionString$SHORT_VERSION + CFBundleVersion$VERSION + LSMinimumSystemVersion14.0 + LSApplicationCategoryTypepublic.app-category.developer-tools + NSHighResolutionCapable + NSPrincipalClassNSApplication + NSHumanReadableCopyrightApache-2.0 · pgbot.dev + CFBundleURLTypes + + CFBundleURLNamedev.pgbot.desktop.auth + CFBundleURLSchemespgbot + + PGBotAuthBrokerURL${PGBOT_AUTH_BROKER_URL:-} + + +PLIST + +echo "→ Signing (ad hoc; use a Developer ID identity for distribution)" +codesign --force --options runtime --sign "${CODESIGN_IDENTITY:--}" "$APP/Contents/Resources/engine/pgbot" +codesign --force --options runtime --sign "${CODESIGN_IDENTITY:--}" "$APP" +codesign --verify --deep --strict "$APP" + +echo "✓ $APP" +echo " engine: $("$APP/Contents/Resources/engine/pgbot" --version) ($(lipo -archs "$APP/Contents/Resources/engine/pgbot"))" +echo " app: $(lipo -archs "$APP/Contents/MacOS/PGBot")" From 97d44c1cb2f3442a20e2b43171679e0af1c425ac Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:03:36 -0800 Subject: [PATCH 4/8] ci: macOS job for the desktop app and `sql run` Runs on macos-14 (Swift 5.10) when desktop/, cmd/, internal/ or the Go module change: PGBotKit unit checks, live engine checks against a Homebrew PostgreSQL 17 (including PSQL mode's read-only guarantees), the sql run superuser integration test, and a PGBot.app build whose bundle, universal engine and signature are verified. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/desktop-macos.yml | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 .github/workflows/desktop-macos.yml diff --git a/.github/workflows/desktop-macos.yml b/.github/workflows/desktop-macos.yml new file mode 100644 index 0000000..55b86a2 --- /dev/null +++ b/.github/workflows/desktop-macos.yml @@ -0,0 +1,56 @@ +name: desktop-macos + +# The native macOS app (desktop/macos) and the engine commands it drives. +on: + push: + branches: [main] + paths: ["desktop/**", "cmd/**", "internal/**", "go.mod", "go.sum", ".github/workflows/desktop-macos.yml"] + pull_request: + paths: ["desktop/**", "cmd/**", "internal/**", "go.mod", "go.sum", ".github/workflows/desktop-macos.yml"] + +permissions: + contents: read + +jobs: + checks: + name: PGBotKit checks + app bundle + # macos-14 ships Xcode 15.4 / Swift 5.10, the toolchain the package targets. + runs-on: macos-14 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - name: unit checks + working-directory: desktop/macos + run: swift run PGBotKitChecks + - name: start PostgreSQL 17 with a pg_monitor role + run: | + brew install postgresql@17 + PGBIN="$(brew --prefix postgresql@17)/bin" + "$PGBIN/initdb" -D "$RUNNER_TEMP/pg" -U postgres --auth=trust >/dev/null + printf "port=55432\nlisten_addresses='127.0.0.1'\nunix_socket_directories=''\n" >> "$RUNNER_TEMP/pg/postgresql.conf" + "$PGBIN/pg_ctl" -D "$RUNNER_TEMP/pg" -l "$RUNNER_TEMP/pg.log" -w start + "$PGBIN/psql" -h 127.0.0.1 -p 55432 -U postgres -q \ + -c "CREATE ROLE pgbot_ro LOGIN PASSWORD 'ro'; GRANT pg_monitor TO pgbot_ro;" + - name: live engine checks (inspect, ask plumbing, PSQL mode read-only guarantees) + env: + PGBOT_TEST_DSN: postgresql://pgbot_ro:ro@127.0.0.1:55432/postgres?sslmode=disable + PGBOT_ENGINE_PATH: ${{ github.workspace }}/bin/pgbot + run: | + CGO_ENABLED=0 go build -o bin/pgbot ./cmd/pgbot + cd desktop/macos && swift run PGBotKitChecks + - name: sql run integration (writes never land, even as superuser) + env: + PGBOT_TEST_SUPERUSER_DSN: postgres://postgres@127.0.0.1:55432/postgres?sslmode=disable + run: go test ./cmd/pgbot/ -run 'Integration_sqlRun' -v + - name: build PGBot.app + run: desktop/macos/scripts/build-app.sh + - name: the bundle is complete and its engine runs + run: | + APP=desktop/macos/build/PGBot.app + test -x "$APP/Contents/MacOS/PGBot" + lipo -archs "$APP/Contents/Resources/engine/pgbot" | grep -q arm64 + lipo -archs "$APP/Contents/Resources/engine/pgbot" | grep -q x86_64 + "$APP/Contents/Resources/engine/pgbot" sql run --help | grep -q "READ ONLY" + codesign --verify --deep "$APP" From 7893f5fc26fae4827cb747240b0733b5b72af422 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:05:57 -0800 Subject: [PATCH 5/8] ci(desktop): run on macos-latest (macos-14 image is retired) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/desktop-macos.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/desktop-macos.yml b/.github/workflows/desktop-macos.yml index 55b86a2..c089868 100644 --- a/.github/workflows/desktop-macos.yml +++ b/.github/workflows/desktop-macos.yml @@ -14,13 +14,15 @@ permissions: jobs: checks: name: PGBotKit checks + app bundle - # macos-14 ships Xcode 15.4 / Swift 5.10, the toolchain the package targets. - runs-on: macos-14 + # The package declares swift-tools-version 5.10 (Swift 5 language mode), so + # the newer Xcode on macos-latest builds it unchanged. + runs-on: macos-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: go.mod + - run: swift --version && xcodebuild -version - name: unit checks working-directory: desktop/macos run: swift run PGBotKitChecks From 3f8ba2dac3b979c05cad7793a021fa6ae6f7bb14 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:12:37 -0800 Subject: [PATCH 6/8] fix(desktop): don't post a second health report right after adding a database Adding a database posts its first health report. The once-a-minute daily report timer then saw a bot that had never had a daily report, past its report hour (09:00 by default), and ran a second inspection, so the chat showed the same report twice. The first report now counts as today's full report, and the due rule moves to AnnouncementLedger.isDailyReportDue, covered by a new check. Verified in the built app: one report after 2.5 minutes, where there used to be two. Co-Authored-By: Claude Opus 5.5 --- desktop/macos/Sources/PGBot/App/AppModel.swift | 6 +++--- .../Sources/PGBotKit/Monitoring/FindingDiff.swift | 11 +++++++++++ desktop/macos/Tests/PGBotKitChecks/main.swift | 13 +++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/desktop/macos/Sources/PGBot/App/AppModel.swift b/desktop/macos/Sources/PGBot/App/AppModel.swift index 085bcbf..a05cf9e 100644 --- a/desktop/macos/Sources/PGBot/App/AppModel.swift +++ b/desktop/macos/Sources/PGBot/App/AppModel.swift @@ -410,6 +410,8 @@ final class AppModel { let planned = NotificationPlanner.plan(botName: bot.displayName, changes: changes ?? FindingChanges.compare(previous: [], current: rec.context.findings, ignoring: bot.schedule.ignoredFindingKeys), scoreBefore: prev?.score.value, scoreAfter: rec.score, ledger: &ledger, prefs: prefs(for: bot)) + // The first report is today's full report; don't repeat it as a "daily" one. + if reason == .first { ledger.lastDailyReport = rec.finishedAt } if reason == .daily { ledger.lastDailyReport = Date() if !settings.disabledCategories.contains(.scheduledReport) { @@ -445,9 +447,7 @@ final class AppModel { guard settings.backgroundMonitoring else { return } let cal = Calendar.current for b in bots where !b.isDemo && b.schedule.enabled { - guard let hour = b.schedule.dailyReportHour, cal.component(.hour, from: now) >= hour else { continue } - let ledger = ledgerFor(b.id) - if let last = ledger.lastDailyReport, cal.isDate(last, inSameDayAs: now) { continue } + guard ledgerFor(b.id).isDailyReportDue(hour: b.schedule.dailyReportHour, now: now, calendar: cal) else { continue } Task { await inspect(b.id, reason: .daily) } } } diff --git a/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift b/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift index d0f4fa5..c473451 100644 --- a/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift +++ b/desktop/macos/Sources/PGBotKit/Monitoring/FindingDiff.swift @@ -47,8 +47,19 @@ public struct AnnouncementLedger: Codable, Sendable, Equatable { /// finding key → severity last announced public var announced: [String: Severity] = [:] public var connectivityDown = false + /// When the user last got a full health report in the chat: the daily + /// report, or the first report right after the database was added. public var lastDailyReport: Date? public init() {} + + /// A full report is due once per calendar day, from `hour` on, unless one + /// has already been shown today. Adding a database at 3 PM shows its first + /// report; that one counts for today, so no second report follows a minute later. + public func isDailyReportDue(hour: Int?, now: Date, calendar: Calendar = .current) -> Bool { + guard let hour, calendar.component(.hour, from: now) >= hour else { return false } + if let last = lastDailyReport, calendar.isDate(last, inSameDayAs: now) { return false } + return true + } } public struct PlannedNotification: Sendable, Equatable { diff --git a/desktop/macos/Tests/PGBotKitChecks/main.swift b/desktop/macos/Tests/PGBotKitChecks/main.swift index 93ce85e..fb9979d 100644 --- a/desktop/macos/Tests/PGBotKitChecks/main.swift +++ b/desktop/macos/Tests/PGBotKitChecks/main.swift @@ -235,6 +235,19 @@ check("connectivity outage announced once, recovery announced once") { let n = NotificationPlanner.plan(botName: "B", changes: .init(), scoreBefore: nil, scoreAfter: s, ledger: &ledger, prefs: .init()) expectEq(n.map(\.dedupKey), ["connectivity|up"]) } +check("daily report: due once a day after its hour, and the first report counts for today") { + var cal = Calendar(identifier: .gregorian); cal.timeZone = TimeZone(identifier: "UTC")! + func at(_ day: Int, _ hour: Int) -> Date { cal.date(from: DateComponents(year: 2026, month: 11, day: day, hour: hour, minute: 5))! } + var l = AnnouncementLedger() + expect(!l.isDailyReportDue(hour: 9, now: at(26, 8), calendar: cal), "not before its hour") + expect(l.isDailyReportDue(hour: 9, now: at(26, 15), calendar: cal), "a database that never reported is due after its hour") + expect(!l.isDailyReportDue(hour: nil, now: at(26, 15), calendar: cal), "no daily report configured") + l.lastDailyReport = at(26, 15) // the first report, right after adding the database at 3 PM + expect(!l.isDailyReportDue(hour: 9, now: at(26, 15).addingTimeInterval(60), calendar: cal), "no second report a minute later") + expect(!l.isDailyReportDue(hour: 9, now: at(26, 23), calendar: cal), "nor later that day") + expect(!l.isDailyReportDue(hour: 9, now: at(27, 8), calendar: cal), "next day, not before the hour") + expect(l.isDailyReportDue(hour: 9, now: at(27, 9), calendar: cal), "next day at the hour") +} check("quiet hours wrap midnight") { var q = QuietHours(); q.enabled = true; q.startHour = 22; q.endHour = 7 let cal = Calendar.current, d = Date() From 532bf381060fb00a5e9c48c480abc4d99e684410 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Thu, 26 Nov 2026 12:31:43 -0800 Subject: [PATCH 7/8] feat(desktop): Chat | PSQL switch next to + in the composer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The composer mode was only reachable from the + menu or ⌘⇧P, and nothing near the input said which mode was on. A two-segment Chat | PSQL switch now sits next to +: the active mode is a raised pill (green for PSQL) that slides between segments, with tooltips and accessibility labels. Also: the \? help rendered its Markdown table as raw pipes (chat messages don't render tables); it is a list now. Co-Authored-By: Claude Opus 5.5 --- .../Features/Chat/ConversationView.swift | 62 +++++++++++++++++++ .../macos/Sources/PGBotKit/PSQL/PSQL.swift | 16 +++-- 2 files changed, 69 insertions(+), 9 deletions(-) diff --git a/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift b/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift index 8716294..ef876fd 100644 --- a/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift +++ b/desktop/macos/Sources/PGBot/Features/Chat/ConversationView.swift @@ -174,6 +174,8 @@ import SwiftUI .help("Actions and model") .accessibilityLabel("Actions") + ComposerModeSwitch(psql: psql) { model.setPSQLMode($0, for: bot.id) } + if psql { Text("\(bot.connection.database)=>") .font(.sys(size: 14, weight: .medium, design: .monospaced)) @@ -247,6 +249,66 @@ import SwiftUI } } +/// Chat | PSQL, next to +: shows which mode the composer is in and switches it. +/// The active segment is a raised pill (green for PSQL); the other stays quiet. +@MainActor struct ComposerModeSwitch: View { + let psql: Bool + let set: (Bool) -> Void + @Namespace private var pill + + var body: some View { + HStack(spacing: 2) { + segment("Chat", symbol: "bubble.left", active: !psql, tint: .primary) { set(false) } + .help("Ask in plain language") + segment("PSQL", symbol: "terminal", active: psql, tint: Palette.healthy, mono: true) { set(true) } + .help("Run read-only SQL and \\d commands (⌘⇧P)") + } + .padding(3) + .frame(height: 38) + .background(Palette.control, in: Capsule()) + .animation(.snappy(duration: 0.22), value: psql) + .accessibilityElement(children: .contain) + .accessibilityLabel("Composer mode") + } + + private func segment(_ title: String, symbol: String, active: Bool, tint: Color, mono: Bool = false, + action: @escaping () -> Void) -> some View { + ModeSegment(title: title, symbol: symbol, active: active, tint: tint, mono: mono, pill: pill, action: action) + } +} + +@MainActor private struct ModeSegment: View { + let title: String, symbol: String, active: Bool, tint: Color, mono: Bool + let pill: Namespace.ID + let action: () -> Void + @State private var hover = false + + var body: some View { + Button(action: action) { + HStack(spacing: 5) { + Image(systemName: symbol).font(.system(size: 11.5, weight: .semibold)) + Text(title).font(.sys(size: 12, weight: .semibold, design: mono ? .monospaced : .default)) + } + .foregroundStyle(active ? AnyShapeStyle(tint) : AnyShapeStyle(.secondary.opacity(hover ? 1 : 0.8))) + .padding(.horizontal, 10) + .frame(maxHeight: .infinity) + .background { + if active { + Capsule().fill(tint == .primary ? Palette.floating : Palette.healthy.opacity(0.16)) + .overlay(Capsule().strokeBorder(tint == .primary ? Palette.hairline.opacity(1.7) : Palette.healthy.opacity(0.45))) + .shadow(color: .black.opacity(0.18), radius: 2, y: 1) + .matchedGeometryEffect(id: "pill", in: pill) + } + } + .contentShape(Capsule()) + } + .buttonStyle(.plain) + .onHover { hover = $0 } + .accessibilityLabel(title) + .accessibilityAddTraits(active ? .isSelected : []) + } +} + /// The model choice lives in the + menu instead of cluttering the composer. @MainActor struct AIModelMenu: View { @Environment(AppModel.self) private var model diff --git a/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift b/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift index 8ecda04..c21571e 100644 --- a/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift +++ b/desktop/macos/Sources/PGBotKit/PSQL/PSQL.swift @@ -178,15 +178,13 @@ public enum PSQL { End a statement with `;` and press Return to run it. Shift-Return adds a line, ↑ and ↓ walk your history. - | Command | Shows | - |---|---| - | `\\d name` | a table's columns and indexes | - | `\\d`, `\\dt`, `\\dv`, `\\dm`, `\\di`, `\\ds` | relations, tables, views, materialized views, indexes, sequences (add `+` for sizes) | - | `\\dn`, `\\df`, `\\dx` | schemas, functions, extensions | - | `\\l`, `\\du` | databases, roles | - | `\\conninfo` | who and where you're connected | - | `\\x` | expanded (one row per record) display | - | `\\q` | back to chat | + - `\\d name`: a table's columns and indexes + - `\\d` `\\dt` `\\dv` `\\dm` `\\di` `\\ds`: relations, tables, views, materialized views, indexes, sequences (add `+` for sizes) + - `\\dn` `\\df` `\\dx`: schemas, functions, extensions + - `\\l` `\\du`: databases, roles + - `\\conninfo`: who and where you're connected + - `\\x`: expanded display, one block per row + - `\\q`: back to chat Patterns work like psql: `\\dt public.order*`. """ From 1e97c6539524a5b2088433fc147c75df30b376f4 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Fri, 27 Nov 2026 22:19:40 -0800 Subject: [PATCH 8/8] docs(desktop): update check counts in README (50 unit + 8 live) Co-Authored-By: Claude Opus 5.5 --- desktop/macos/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/desktop/macos/README.md b/desktop/macos/README.md index 470f3c4..5f8f5a0 100644 --- a/desktop/macos/README.md +++ b/desktop/macos/README.md @@ -30,7 +30,7 @@ open desktop/macos/build/PGBot.app ```sh cd desktop/macos -swift run PGBotKitChecks # 49 unit checks +swift run PGBotKitChecks # 50 unit checks PGBOT_TEST_DSN='postgresql://pgbot_ro:…@127.0.0.1:5432/postgres?sslmode=disable' \ PGBOT_ENGINE_PATH=../../bin/pgbot swift run PGBotKitChecks # + 8 live-engine checks ```