From d5168a7f8b93989b43f27ba988a24e8343af7534 Mon Sep 17 00:00:00 2001 From: hawkfry Date: Sun, 15 Mar 2026 22:53:18 +0000 Subject: [PATCH 1/3] test: expand cli and client command coverage --- internal/cli/command_groups_test.go | 480 ++++++++++++++++++++++++++++ internal/client/wrappers_test.go | 319 ++++++++++++++++++ 2 files changed, 799 insertions(+) create mode 100644 internal/cli/command_groups_test.go create mode 100644 internal/client/wrappers_test.go diff --git a/internal/cli/command_groups_test.go b/internal/cli/command_groups_test.go new file mode 100644 index 0000000..f07cb56 --- /dev/null +++ b/internal/cli/command_groups_test.go @@ -0,0 +1,480 @@ +package cli + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/omni-co/omni-cli/internal/auth" + "github.com/omni-co/omni-cli/internal/config" +) + +const testCommandUUID = "550e8400-e29b-41d4-a716-446655440000" + +func TestRunAdminUsersAndGroupsList(t *testing.T) { + var sawUsers bool + var sawGroups bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/scim/v2/Users": + sawUsers = true + if r.URL.Query().Get("count") != "5" || r.URL.Query().Get("startIndex") != "2" { + t.Fatalf("unexpected users query: %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"Resources":[{"id":"` + testCommandUUID + `","displayName":"Jamie Fry","userName":"jamie@example.com"}],"itemsPerPage":1,"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"startIndex":1,"totalResults":1}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/scim/v2/Groups": + sawGroups = true + if r.URL.Query().Get("count") != "3" || r.URL.Query().Get("startIndex") != "4" { + t.Fatalf("unexpected groups query: %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"Resources":[{"id":"` + testCommandUUID + `","displayName":"Analysts"}],"itemsPerPage":1,"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"startIndex":1,"totalResults":1}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + orgRT := testRuntime(server.URL, "org-token", "org") + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAdmin(orgRT, []string{"users", "list", "--count", "5", "--start-index", "2"}) + }) + if exit != 0 || !strings.Contains(stdout, `"Resources"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("admin users list failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runAdmin(orgRT, []string{"groups", "list", "--count", "3", "--start-index", "4"}) + }) + if exit != 0 || !strings.Contains(stdout, `"Analysts"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("admin groups list failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + if !sawUsers || !sawGroups { + t.Fatalf("expected both admin endpoints to be exercised, got users=%v groups=%v", sawUsers, sawGroups) + } + + plainRT := testRuntime(server.URL, "pat-token", "pat") + _, stderr, exit = captureRuntimeIO(t, func() int { + return runAdmin(plainRT, []string{"users", "list"}) + }) + if exit != 1 || !strings.Contains(stderr, "admin commands require an org API key") { + t.Fatalf("expected org-key guard, got exit=%d stderr=%q", exit, stderr) + } +} + +func TestRunAgenticCommands(t *testing.T) { + tmp := t.TempDir() + payloadPath := writeTempJSON(t, tmp, "agentic.json", `{"prompt":"show revenue","modelId":"`+testCommandUUID+`"}`) + + var sawSubmit bool + var sawStatus bool + var sawCancel bool + var sawResult bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/agentic/jobs": + sawSubmit = true + body := mustReadAll(t, r) + if !strings.Contains(body, `"prompt":"show revenue"`) { + t.Fatalf("unexpected submit body %q", body) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"jobId":"` + testCommandUUID + `","conversationId":"` + testCommandUUID + `"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/agentic/jobs/"+testCommandUUID: + sawStatus = true + _, _ = w.Write([]byte(`{"id":"` + testCommandUUID + `","state":"COMPLETE","conversationId":"` + testCommandUUID + `","createdAt":"2025-01-01T00:00:00Z","organizationId":"` + testCommandUUID + `","prompt":"show revenue","updatedAt":"2025-01-01T00:00:00Z","userId":"` + testCommandUUID + `","branchId":null,"modelId":null,"topicName":null}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/agentic/jobs/"+testCommandUUID+"/cancel": + sawCancel = true + _, _ = w.Write([]byte(`{"jobId":"` + testCommandUUID + `","state":"CANCELLED"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/agentic/jobs/"+testCommandUUID+"/result": + sawResult = true + _, _ = w.Write([]byte(`{"id":"` + testCommandUUID + `","state":"COMPLETE","conversationId":"` + testCommandUUID + `","createdAt":"2025-01-01T00:00:00Z","organizationId":"` + testCommandUUID + `","prompt":"show revenue","resultSummary":"done","updatedAt":"2025-01-01T00:00:00Z","userId":"` + testCommandUUID + `","branchId":null,"modelId":null,"topicName":null}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := testRuntime(server.URL, "pat-token", "pat") + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAgentic(rt, []string{"submit", "--file", payloadPath}) + }) + if exit != 0 || !strings.Contains(stdout, `"jobId": "`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("agentic submit failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + for _, sub := range []string{"status", "cancel", "result"} { + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runAgentic(rt, []string{sub, testCommandUUID}) + }) + if exit != 0 || !strings.Contains(stdout, testCommandUUID) || strings.TrimSpace(stderr) != "" { + t.Fatalf("agentic %s failed: exit=%d stdout=%q stderr=%q", sub, exit, stdout, stderr) + } + } + + if !sawSubmit || !sawStatus || !sawCancel || !sawResult { + t.Fatalf("expected all agentic endpoints, got submit=%v status=%v cancel=%v result=%v", sawSubmit, sawStatus, sawCancel, sawResult) + } +} + +func TestRunAICommands(t *testing.T) { + tmp := t.TempDir() + contextPath := writeTempJSON(t, tmp, "context.json", `{"fields":["orders.id"]}`) + + var sawGenerate bool + var sawWorkbook bool + var sawPickTopic bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/api/v1/ai/generate-query": + body := mustReadAll(t, r) + isWorkbook := strings.Contains(body, `"workbookUrl":true`) + if isWorkbook { + sawWorkbook = true + } else { + sawGenerate = true + } + if !strings.Contains(body, `"modelId":"`+testCommandUUID+`"`) || !strings.Contains(body, `"prompt":"show revenue"`) { + t.Fatalf("unexpected ai generate body %q", body) + } + if !isWorkbook && !strings.Contains(body, `"contextQuery":{"fields":["orders.id"]}`) { + t.Fatalf("expected context query body, got %q", body) + } + _, _ = w.Write([]byte(`{"topic":"orders","query":{"ok":true},"error":null}`)) + case "/api/v1/ai/pick-topic": + sawPickTopic = true + body := mustReadAll(t, r) + if !strings.Contains(body, `"potentialTopicNames":["orders","customers"]`) { + t.Fatalf("unexpected ai pick-topic body %q", body) + } + _, _ = w.Write([]byte(`{"topicId":"orders"}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := testRuntime(server.URL, "pat-token", "pat") + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runAI(rt, []string{"generate-query", "--model-id", testCommandUUID, "--prompt", "show revenue", "--current-topic-name", "orders", "--branch-id", testCommandUUID, "--structured", "--context-query-file", contextPath}) + }) + if exit != 0 || !strings.Contains(stdout, `"topic": "orders"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("ai generate-query failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runAI(rt, []string{"workbook", "--model-id", testCommandUUID, "--prompt", "show revenue"}) + }) + if exit != 0 || !strings.Contains(stdout, `"topic": "orders"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("ai workbook failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + stdout, stderr, exit = captureRuntimeIO(t, func() int { + return runAI(rt, []string{"pick-topic", "--model-id", testCommandUUID, "--prompt", "show revenue", "--potential-topic-names", "orders, customers"}) + }) + if exit != 0 || !strings.Contains(stdout, `"topicId": "orders"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("ai pick-topic failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + + if !sawGenerate || !sawWorkbook || !sawPickTopic { + t.Fatalf("expected all ai endpoints, got generate=%v workbook=%v pickTopic=%v", sawGenerate, sawWorkbook, sawPickTopic) + } +} + +func TestRunDashboardsAndEmbedCommands(t *testing.T) { + tmp := t.TempDir() + downloadPath := writeTempJSON(t, tmp, "download.json", `{"format":"pdf"}`) + filtersPath := writeTempJSON(t, tmp, "filters.json", `{"filters":[]}`) + embedPath := writeTempJSON(t, tmp, "embed.json", `{"userId":"`+testCommandUUID+`"}`) + + const dashboardID = "wk_abc123" + const jobID = "job-123" + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/dashboards/"+dashboardID+"/download": + if r.URL.Query().Get("userId") != "member-1" { + t.Fatalf("unexpected download query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"jobId":"` + jobID + `"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/dashboards/"+dashboardID+"/download/"+jobID+"/status": + if r.URL.Query().Get("userId") != "member-1" { + t.Fatalf("unexpected dashboard query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"status":"ready"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/dashboards/"+dashboardID+"/download/"+jobID: + if r.URL.Query().Get("userId") != "member-1" { + t.Fatalf("unexpected dashboard file query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"url":"https://example.com/download.pdf"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/dashboards/"+dashboardID+"/filters": + if r.URL.Query().Get("userId") != "member-1" { + t.Fatalf("unexpected filters get query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"filters":[]}`)) + case r.Method == http.MethodPatch && r.URL.Path == "/api/v1/dashboards/"+dashboardID+"/filters": + if r.URL.Query().Get("userId") != "member-1" { + t.Fatalf("unexpected filters update query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"updated":true}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/embed/sso/generate-session": + body := mustReadAll(t, r) + if !strings.Contains(body, `"userId":"`+testCommandUUID+`"`) { + t.Fatalf("unexpected embed body %q", body) + } + _, _ = w.Write([]byte(`{"url":"https://embed.example.com/session"}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := testRuntime(server.URL, "org-token", "org") + + for _, args := range [][]string{ + {"download", "--file", downloadPath, "--user-id", "member-1", dashboardID}, + {"download-status", "--user-id", "member-1", dashboardID, jobID}, + {"download-file", "--user-id", "member-1", dashboardID, jobID}, + {"filters", "get", "--user-id", "member-1", dashboardID}, + {"filters", "update", "--file", filtersPath, "--user-id", "member-1", dashboardID}, + } { + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runDashboards(rt, args) + }) + if exit != 0 || strings.TrimSpace(stderr) != "" { + t.Fatalf("dashboards command %v failed: exit=%d stdout=%q stderr=%q", args, exit, stdout, stderr) + } + } + + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runEmbed(rt, []string{"sso", "generate-session", "--file", embedPath}) + }) + if exit != 0 || !strings.Contains(stdout, `embed.example.com/session`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("embed sso generate-session failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } +} + +func TestRunLabelsCommands(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/labels": + _, _ = w.Write([]byte(`{"records":[{"name":"finance"}]}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/labels/finance": + _, _ = w.Write([]byte(`{"name":"finance"}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/labels": + body := mustReadAll(t, r) + if r.URL.Query().Get("userId") != "member-1" || !strings.Contains(body, `"homepage":true`) { + t.Fatalf("unexpected label create request query=%q body=%q", r.URL.RawQuery, body) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"name":"finance"}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/labels/finance": + body := mustReadAll(t, r) + if !strings.Contains(body, `"name":"finance-updated"`) { + t.Fatalf("unexpected label update body %q", body) + } + _, _ = w.Write([]byte(`{"name":"finance-updated"}`)) + case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/labels/finance": + if r.URL.Query().Get("userId") != "member-1" { + t.Fatalf("unexpected label delete query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"deleted":true}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := testRuntime(server.URL, "org-token", "org") + + for _, args := range [][]string{ + {"list"}, + {"get", "finance"}, + {"create", "--homepage", "true", "--user-id", "member-1", "finance"}, + {"update", "--new-name", "finance-updated", "finance"}, + {"delete", "--user-id", "member-1", "finance"}, + } { + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runLabels(rt, args) + }) + if exit != 0 || strings.TrimSpace(stderr) != "" { + t.Fatalf("labels command %v failed: exit=%d stdout=%q stderr=%q", args, exit, stdout, stderr) + } + } + + _, stderr, exit := captureRuntimeIO(t, func() int { + return runLabels(rt, []string{"update", "finance"}) + }) + if exit != 2 || !strings.Contains(stderr, "no changes provided") { + t.Fatalf("expected no-changes usage error, got exit=%d stderr=%q", exit, stderr) + } +} + +func TestRunSchedulesCommands(t *testing.T) { + tmp := t.TempDir() + createPath := writeTempJSON(t, tmp, "schedule-create.json", `{"name":"Daily"}`) + recipientsPath := writeTempJSON(t, tmp, "recipients.json", `{"userIds":["`+testCommandUUID+`"]}`) + ownershipPath := writeTempJSON(t, tmp, "ownership.json", `{"userId":"`+testCommandUUID+`"}`) + + var transferCalls int + var sawTransferFile bool + var sawTransferFlag bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/schedules": + if r.URL.Query().Get("cursor") != "abc" || r.URL.Query().Get("pageSize") != "10" || r.URL.Query().Get("q") != "daily" { + t.Fatalf("unexpected schedules list query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"records":[]}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/schedules": + if r.URL.Query().Get("userId") != testCommandUUID { + t.Fatalf("unexpected schedules create query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"id":"` + testCommandUUID + `"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/schedules/"+testCommandUUID: + _, _ = w.Write([]byte(`{"id":"` + testCommandUUID + `"}`)) + case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/schedules/"+testCommandUUID: + _, _ = w.Write([]byte(`{"deleted":true}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testCommandUUID: + _, _ = w.Write([]byte(`{"updated":true}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/pause": + _, _ = w.Write([]byte(`{"status":"paused"}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/resume": + _, _ = w.Write([]byte(`{"status":"resumed"}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/trigger": + _, _ = w.Write([]byte(`{"status":"triggered"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/recipients": + _, _ = w.Write([]byte(`{"recipients":[]}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/add-recipients": + _, _ = w.Write([]byte(`{"added":true}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/remove-recipients": + _, _ = w.Write([]byte(`{"removed":true}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testCommandUUID+"/transfer-ownership": + body := mustReadAll(t, r) + if body != `{"userId":"`+testCommandUUID+`"}` { + t.Fatalf("unexpected transfer ownership body %q", body) + } + transferCalls++ + if transferCalls == 1 { + sawTransferFlag = true + } else { + sawTransferFile = true + } + _, _ = w.Write([]byte(`{"transferred":true}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := testRuntime(server.URL, "org-token", "org") + + cases := []struct { + args []string + }{ + {[]string{"list", "--cursor", "abc", "--page-size", "10", "--q", "daily"}}, + {[]string{"create", "--file", createPath, "--user-id", testCommandUUID}}, + {[]string{"get", testCommandUUID}}, + {[]string{"update", testCommandUUID}}, + {[]string{"delete", testCommandUUID}}, + {[]string{"pause", testCommandUUID}}, + {[]string{"resume", testCommandUUID}}, + {[]string{"trigger", testCommandUUID}}, + {[]string{"recipients", "get", testCommandUUID}}, + {[]string{"recipients", "add", "--file", recipientsPath, testCommandUUID}}, + {[]string{"recipients", "remove", "--file", recipientsPath, testCommandUUID}}, + {[]string{"transfer-ownership", "--user-id", testCommandUUID, testCommandUUID}}, + {[]string{"transfer-ownership", "--file", ownershipPath, testCommandUUID}}, + } + + for i, tc := range cases { + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runSchedules(rt, tc.args) + }) + if exit != 0 || strings.TrimSpace(stderr) != "" { + t.Fatalf("schedules command #%d %v failed: exit=%d stdout=%q stderr=%q", i, tc.args, exit, stdout, stderr) + } + } + + if !sawTransferFlag || !sawTransferFile { + t.Fatalf("expected transfer ownership to exercise both flag and file paths, got flag=%v file=%v", sawTransferFlag, sawTransferFile) + } +} + +func TestRunQueryRunWaitsForResults(t *testing.T) { + tmp := t.TempDir() + queryPath := writeTempJSON(t, tmp, "query.json", `{"query":{"fields":["orders.id"]}}`) + var sawRun bool + var sawWait bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/query/run": + sawRun = true + body := mustReadAll(t, r) + if !strings.Contains(body, `"resultType":"json"`) { + t.Fatalf("expected query result type in body, got %q", body) + } + _, _ = w.Write([]byte(`{"jobIds":["` + testCommandUUID + `"]}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/query/wait": + sawWait = true + if r.URL.Query().Get("jobIds") != testCommandUUID { + t.Fatalf("unexpected wait query %q", r.URL.RawQuery) + } + _, _ = w.Write([]byte(`{"results":[{"ok":true}]}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.Path) + } + })) + defer server.Close() + + rt := testRuntime(server.URL, "pat-token", "pat") + stdout, stderr, exit := captureRuntimeIO(t, func() int { + return runQuery(rt, []string{"run", "--file", queryPath, "--result-type", "json", "--wait"}) + }) + if exit != 0 || !strings.Contains(stdout, `"results"`) || strings.TrimSpace(stderr) != "" { + t.Fatalf("query run failed: exit=%d stdout=%q stderr=%q", exit, stdout, stderr) + } + if !sawRun || !sawWait { + t.Fatalf("expected run and wait endpoints, got run=%v wait=%v", sawRun, sawWait) + } +} + +func testRuntime(baseURL, token, tokenType string) *runtime { + return &runtime{ + JSON: true, + Resolved: &auth.Resolved{ + ProfileName: "default", + Profile: config.Profile{ + BaseURL: baseURL, + Token: token, + TokenType: tokenType, + }, + }, + } +} + +func writeTempJSON(t *testing.T, dir, name, body string) string { + t.Helper() + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatalf("write temp json %s: %v", name, err) + } + return path +} diff --git a/internal/client/wrappers_test.go b/internal/client/wrappers_test.go new file mode 100644 index 0000000..9b22988 --- /dev/null +++ b/internal/client/wrappers_test.go @@ -0,0 +1,319 @@ +package client + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/google/uuid" +) + +func TestAdminAndLabelWrappers(t *testing.T) { + const testUUID = "550e8400-e29b-41d4-a716-446655440000" + var sawUsers bool + var sawGroups bool + var sawListLabels bool + var sawGetLabel bool + var sawCreateLabel bool + var sawUpdateLabel bool + var sawDeleteLabel bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Header.Get("Authorization") != "Bearer token-123" { + t.Fatalf("missing auth header: %q", r.Header.Get("Authorization")) + } + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/scim/v2/Users": + sawUsers = true + assertQueryValue(t, r.URL, "count", "5") + assertQueryValue(t, r.URL, "startIndex", "2") + assertQueryValue(t, r.URL, "filter", `userName eq "jamie@example.com"`) + _, _ = w.Write([]byte(`{"Resources":[],"itemsPerPage":0,"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"startIndex":1,"totalResults":0}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/scim/v2/Groups": + sawGroups = true + assertQueryValue(t, r.URL, "count", "7") + assertQueryValue(t, r.URL, "startIndex", "3") + _, _ = w.Write([]byte(`{"Resources":[],"itemsPerPage":0,"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],"startIndex":1,"totalResults":0}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/labels": + sawListLabels = true + _, _ = w.Write([]byte(`{"records":[]}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/labels/finance": + sawGetLabel = true + _, _ = w.Write([]byte(`{"name":"finance"}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/labels": + sawCreateLabel = true + assertQueryValue(t, r.URL, "userId", "member-1") + body := mustReadBody(t, r) + if !strings.Contains(body, `"name":"finance"`) || !strings.Contains(body, `"homepage":true`) { + t.Fatalf("unexpected label create body %q", body) + } + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"name":"finance"}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/labels/finance": + sawUpdateLabel = true + assertQueryValue(t, r.URL, "userId", "member-1") + body := mustReadBody(t, r) + if !strings.Contains(body, `"name":"finance-2"`) || !strings.Contains(body, `"verified":true`) { + t.Fatalf("unexpected label update body %q", body) + } + _, _ = w.Write([]byte(`{"name":"finance-2"}`)) + case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/labels/finance": + sawDeleteLabel = true + assertQueryValue(t, r.URL, "userId", "member-1") + _, _ = w.Write([]byte(`{"deleted":true}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.String()) + } + })) + defer server.Close() + + cli := mustNewClient(t, server.URL) + ctx := context.Background() + + if _, err := cli.ListSCIMUsers(ctx, 5, 2, `userName eq "jamie@example.com"`); err != nil { + t.Fatalf("ListSCIMUsers: %v", err) + } + if _, err := cli.ListSCIMGroups(ctx, 7, 3); err != nil { + t.Fatalf("ListSCIMGroups: %v", err) + } + if _, err := cli.ListLabels(ctx); err != nil { + t.Fatalf("ListLabels: %v", err) + } + if _, err := cli.GetLabel(ctx, "finance"); err != nil { + t.Fatalf("GetLabel: %v", err) + } + home := true + if _, err := cli.CreateLabel(ctx, "finance", &home, nil, "member-1"); err != nil { + t.Fatalf("CreateLabel: %v", err) + } + newName := "finance-2" + verified := true + if _, err := cli.UpdateLabel(ctx, "finance", &newName, nil, &verified, "member-1"); err != nil { + t.Fatalf("UpdateLabel: %v", err) + } + if _, err := cli.DeleteLabel(ctx, "finance", "member-1"); err != nil { + t.Fatalf("DeleteLabel: %v", err) + } + + if !sawUsers || !sawGroups || !sawListLabels || !sawGetLabel || !sawCreateLabel || !sawUpdateLabel || !sawDeleteLabel { + t.Fatalf("missing wrapper calls: users=%v groups=%v list=%v get=%v create=%v update=%v delete=%v", sawUsers, sawGroups, sawListLabels, sawGetLabel, sawCreateLabel, sawUpdateLabel, sawDeleteLabel) + } + _ = testUUID +} + +func TestScheduleAIAndDashboardWrappers(t *testing.T) { + const testUUID = "550e8400-e29b-41d4-a716-446655440000" + id := uuid.MustParse(testUUID) + var sawListSchedules bool + var sawCreateSchedule bool + var sawScheduleLifecycle int + var sawRecipients int + var sawAI int + var sawAgentic int + var sawDashboards int + var sawEmbed bool + var sawUserAttributes bool + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/schedules": + sawListSchedules = true + assertQueryValue(t, r.URL, "cursor", "abc") + assertQueryValue(t, r.URL, "pageSize", "10") + assertQueryValue(t, r.URL, "q", "daily") + _, _ = w.Write([]byte(`{"records":[]}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/schedules": + sawCreateSchedule = true + assertQueryValue(t, r.URL, "userId", testUUID) + _, _ = w.Write([]byte(`{"id":"` + testUUID + `"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/schedules/"+testUUID: + sawScheduleLifecycle++ + _, _ = w.Write([]byte(`{"id":"` + testUUID + `"}`)) + case r.Method == http.MethodDelete && r.URL.Path == "/api/v1/schedules/"+testUUID: + sawScheduleLifecycle++ + _, _ = w.Write([]byte(`{"deleted":true}`)) + case r.Method == http.MethodPut && r.URL.Path == "/api/v1/schedules/"+testUUID: + sawScheduleLifecycle++ + _, _ = w.Write([]byte(`{"updated":true}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/pause"): + sawScheduleLifecycle++ + _, _ = w.Write([]byte(`{"status":"paused"}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/resume"): + sawScheduleLifecycle++ + _, _ = w.Write([]byte(`{"status":"resumed"}`)) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/trigger"): + sawScheduleLifecycle++ + _, _ = w.Write([]byte(`{"status":"triggered"}`)) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/recipients"): + sawRecipients++ + _, _ = w.Write([]byte(`{"recipients":[]}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/add-recipients"): + sawRecipients++ + _, _ = w.Write([]byte(`{"added":true}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/remove-recipients"): + sawRecipients++ + _, _ = w.Write([]byte(`{"removed":true}`)) + case r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/transfer-ownership"): + sawRecipients++ + _, _ = w.Write([]byte(`{"transferred":true}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/ai/generate-query": + sawAI++ + _, _ = w.Write([]byte(`{"topic":"orders","query":{"ok":true},"error":null}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/ai/pick-topic": + sawAI++ + _, _ = w.Write([]byte(`{"topicId":"orders"}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/agentic/jobs": + sawAgentic++ + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"jobId":"` + testUUID + `","conversationId":"` + testUUID + `"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/agentic/jobs/"+testUUID: + sawAgentic++ + _, _ = w.Write([]byte(`{"id":"` + testUUID + `","state":"COMPLETE","conversationId":"` + testUUID + `","createdAt":"2025-01-01T00:00:00Z","organizationId":"` + testUUID + `","prompt":"show revenue","updatedAt":"2025-01-01T00:00:00Z","userId":"` + testUUID + `","branchId":null,"modelId":null,"topicName":null}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/agentic/jobs/"+testUUID+"/cancel": + sawAgentic++ + _, _ = w.Write([]byte(`{"jobId":"` + testUUID + `","state":"CANCELLED"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/agentic/jobs/"+testUUID+"/result": + sawAgentic++ + _, _ = w.Write([]byte(`{"id":"` + testUUID + `","state":"COMPLETE","conversationId":"` + testUUID + `","createdAt":"2025-01-01T00:00:00Z","organizationId":"` + testUUID + `","prompt":"show revenue","resultSummary":"done","updatedAt":"2025-01-01T00:00:00Z","userId":"` + testUUID + `","branchId":null,"modelId":null,"topicName":null}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/dashboards/wk_abc/download": + sawDashboards++ + assertQueryValue(t, r.URL, "userId", "member-1") + _, _ = w.Write([]byte(`{"jobId":"job-123"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/dashboards/wk_abc/download/job-123/status": + sawDashboards++ + _, _ = w.Write([]byte(`{"status":"ready"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/dashboards/wk_abc/download/job-123": + sawDashboards++ + _, _ = w.Write([]byte(`{"url":"https://example.com/out.pdf"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/dashboards/wk_abc/filters": + sawDashboards++ + _, _ = w.Write([]byte(`{"filters":[]}`)) + case r.Method == http.MethodPatch && r.URL.Path == "/api/v1/dashboards/wk_abc/filters": + sawDashboards++ + _, _ = w.Write([]byte(`{"updated":true}`)) + case r.Method == http.MethodPost && r.URL.Path == "/api/v1/embed/sso/generate-session": + sawEmbed = true + _, _ = w.Write([]byte(`{"url":"https://embed.example.com/session"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/api/v1/user-attributes": + sawUserAttributes = true + _, _ = w.Write([]byte(`{"records":[]}`)) + default: + t.Fatalf("unexpected %s %s", r.Method, r.URL.String()) + } + })) + defer server.Close() + + cli := mustNewClient(t, server.URL) + ctx := context.Background() + + if _, err := cli.ListSchedules(ctx, "abc", 10, "daily"); err != nil { + t.Fatalf("ListSchedules: %v", err) + } + if _, err := cli.CreateSchedule(ctx, &id, []byte(`{"name":"Daily"}`)); err != nil { + t.Fatalf("CreateSchedule: %v", err) + } + if _, err := cli.GetSchedule(ctx, id); err != nil { + t.Fatalf("GetSchedule: %v", err) + } + if _, err := cli.DeleteSchedule(ctx, id); err != nil { + t.Fatalf("DeleteSchedule: %v", err) + } + if _, err := cli.UpdateSchedule(ctx, id); err != nil { + t.Fatalf("UpdateSchedule: %v", err) + } + if _, err := cli.PauseSchedule(ctx, id); err != nil { + t.Fatalf("PauseSchedule: %v", err) + } + if _, err := cli.ResumeSchedule(ctx, id); err != nil { + t.Fatalf("ResumeSchedule: %v", err) + } + if _, err := cli.TriggerSchedule(ctx, id); err != nil { + t.Fatalf("TriggerSchedule: %v", err) + } + if _, err := cli.GetScheduleRecipients(ctx, id); err != nil { + t.Fatalf("GetScheduleRecipients: %v", err) + } + if _, err := cli.AddScheduleRecipients(ctx, id, []byte(`{"userIds":["`+testUUID+`"]}`)); err != nil { + t.Fatalf("AddScheduleRecipients: %v", err) + } + if _, err := cli.RemoveScheduleRecipients(ctx, id, []byte(`{"userIds":["`+testUUID+`"]}`)); err != nil { + t.Fatalf("RemoveScheduleRecipients: %v", err) + } + if _, err := cli.TransferScheduleOwnership(ctx, id, []byte(`{"userId":"`+testUUID+`"}`)); err != nil { + t.Fatalf("TransferScheduleOwnership: %v", err) + } + if _, err := cli.AIGenerateQuery(ctx, []byte(`{"modelId":"`+testUUID+`","prompt":"show revenue"}`)); err != nil { + t.Fatalf("AIGenerateQuery: %v", err) + } + if _, err := cli.AIPickTopic(ctx, []byte(`{"modelId":"`+testUUID+`","prompt":"show revenue"}`)); err != nil { + t.Fatalf("AIPickTopic: %v", err) + } + if _, err := cli.SubmitAgenticJob(ctx, []byte(`{"modelId":"`+testUUID+`","prompt":"show revenue"}`)); err != nil { + t.Fatalf("SubmitAgenticJob: %v", err) + } + if _, err := cli.GetAgenticJobStatus(ctx, id); err != nil { + t.Fatalf("GetAgenticJobStatus: %v", err) + } + if _, err := cli.CancelAgenticJob(ctx, id); err != nil { + t.Fatalf("CancelAgenticJob: %v", err) + } + if _, err := cli.GetAgenticJobResult(ctx, id); err != nil { + t.Fatalf("GetAgenticJobResult: %v", err) + } + if _, err := cli.DashboardDownload(ctx, "wk_abc", "member-1", []byte(`{"format":"pdf"}`)); err != nil { + t.Fatalf("DashboardDownload: %v", err) + } + if _, err := cli.DashboardDownloadStatus(ctx, "wk_abc", "job-123", "member-1"); err != nil { + t.Fatalf("DashboardDownloadStatus: %v", err) + } + if _, err := cli.DashboardDownloadFile(ctx, "wk_abc", "job-123", "member-1"); err != nil { + t.Fatalf("DashboardDownloadFile: %v", err) + } + if _, err := cli.GetDashboardFilters(ctx, "wk_abc", "member-1"); err != nil { + t.Fatalf("GetDashboardFilters: %v", err) + } + if _, err := cli.UpdateDashboardFilters(ctx, "wk_abc", "member-1", []byte(`{"filters":[]}`)); err != nil { + t.Fatalf("UpdateDashboardFilters: %v", err) + } + if _, err := cli.GenerateEmbedSSOSession(ctx, []byte(`{"userId":"`+testUUID+`"}`)); err != nil { + t.Fatalf("GenerateEmbedSSOSession: %v", err) + } + if _, err := cli.ListUserAttributes(ctx); err != nil { + t.Fatalf("ListUserAttributes: %v", err) + } + + if !sawListSchedules || !sawCreateSchedule || sawScheduleLifecycle != 6 || sawRecipients != 4 || sawAI != 2 || sawAgentic != 4 || sawDashboards != 5 || !sawEmbed || !sawUserAttributes { + t.Fatalf("unexpected wrapper counts: schedules=%v create=%v lifecycle=%d recipients=%d ai=%d agentic=%d dashboards=%d embed=%v attrs=%v", sawListSchedules, sawCreateSchedule, sawScheduleLifecycle, sawRecipients, sawAI, sawAgentic, sawDashboards, sawEmbed, sawUserAttributes) + } +} + +func mustNewClient(t *testing.T, baseURL string) *Client { + t.Helper() + cli, err := New(baseURL, "token-123") + if err != nil { + t.Fatalf("New: %v", err) + } + return cli +} + +func mustReadBody(t *testing.T, r *http.Request) string { + t.Helper() + body, err := io.ReadAll(r.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + return string(body) +} + +func assertQueryValue(t *testing.T, u *url.URL, key, want string) { + t.Helper() + if got := u.Query().Get(key); got != want { + t.Fatalf("expected query %s=%q, got %q", key, want, got) + } +} From b4f7e3c240255ae804fbc6f30c1a6de4983a0b0c Mon Sep 17 00:00:00 2001 From: hawkfry Date: Sun, 15 Mar 2026 23:04:16 +0000 Subject: [PATCH 2/3] docs: update README to clarify CLI purpose and features, emphasizing automation and command contract --- README.md | 366 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 201 insertions(+), 165 deletions(-) diff --git a/README.md b/README.md index 64f9f9d..5dbfc98 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,40 @@ # EARLY ALPHA -This CLI is not yet suitable for use. Made public early to allow comments and early contributers +This repository is public early so the CLI contract can be reviewed in the open. Expect breaking changes while the command surface, auth flows, and automation guarantees are still settling. # omni-cli -Go CLI scaffold for Omni API. - -## Status - -This scaffold now uses generated typed Go client code from Omni OpenAPI. -Agent usage mapping is documented in `docs/agent-command-map.md`. - -## Features in this scaffold - -- Profile-based auth in `~/.omni/config.json` -- Supports PAT auth, org API keys, or both in one profile -- Token storage backends: `keychain` (macOS) or `config` fallback -- Config precedence: flag > env > config file -- `omni setup` wizard (interactive + non-interactive) -- `omni doctor` capability checks (base/query/admin) -- `omni completion` scripts for `bash`, `zsh`, `fish` -- Core resource commands: `documents`, `models`, `connections`, `folders`, `labels`, `schedules` (including create/update/delete/permissions flows) -- Org-admin command groups for `users` and `scim` management -- Omni AI command group for topic selection and natural-language query generation -- Agentic async job command group (`agentic`) -- Dashboard download/filter command group (`dashboards`) -- Embed SSO session command group (`embed`) -- Unstable API command group (`unstable`) -- User attribute definitions command group (`user-attributes`) -- Escape hatch for complete coverage: `omni api call` for authenticated raw endpoint calls -- Org-key admin commands: `admin users list`, `admin groups list` -- Query flow with optional async wait call -- Retry/backoff for idempotent API requests (`429`, `502`, `503`, `504`) -- JSON output mode for scripting -- Machine-readable CLI schema via `omni schema [command-path]` -- Stable automation exit-code contract via `omni exit-codes` -- Global flags can be provided before or after command path -- OpenAPI-driven typed client generation (`oapi-codegen`) -- CI workflow and GoReleaser packaging config - -## Folder layout - -- `cmd/omni`: main entrypoint -- `internal/cli`: command handlers -- `internal/config`: config load/save -- `internal/auth`: profile and token resolution -- `internal/client`: Omni HTTP client wrapper -- `internal/client/gen`: generated OpenAPI client code -- `internal/output`: human/json output helpers -- `api/openapi.json`: source spec (replace with your instance spec) -- `scripts/update_openapi.sh`: fetch and validate instance OpenAPI -- `scripts/generate_client.sh`: normalize 3.1 schema and regenerate client - -## Global flags - -- `--profile` -- `--url` -- `--token` -- `--auth pat|org` -- `--token-type pat|org` (legacy override) -- `--config` -- `--json` -- `--plain` -- `--no-input` -- `--verbose` - -## Environment variables +Automation-first Omni CLI for agents, workflows, and machine-to-machine use. -- `OMNI_PROFILE` -- `OMNI_URL` -- `OMNI_AUTH` -- `OMNI_ORG_KEY` -- `OMNI_PAT` (manual override; PAT is normally acquired by browser login) -- `OMNI_TOKEN` -- `OMNI_TOKEN_TYPE` -- `OMNI_CONFIG` -- `OMNI_PLAIN` -- `OMNI_NO_INPUT` -- `OMNI_ENABLE_COMMANDS` +This repository is not trying to be a human-first terminal app. The primary goal is a stable command contract that other tools can call safely: -## Shell completion +- JSON-first output for automation +- stable exit codes +- machine-readable command discovery via `omni schema` +- explicit auth/profile handling +- raw API access via `omni api call` -```bash -# zsh -mkdir -p ~/.zsh/completions -omni completion zsh > ~/.zsh/completions/_omni +The CLI is built from a generated Omni OpenAPI client plus handwritten command and auth logic. Agent usage mapping is documented in [docs/agent-command-map.md](docs/agent-command-map.md). -# bash -omni completion bash > ~/.local/share/bash-completion/completions/omni +## What The Repo Does Today -# fish -omni completion fish > ~/.config/fish/completions/omni.fish -``` +- wraps the Omni API in typed command groups such as `documents`, `models`, `connections`, `folders`, `labels`, `schedules`, `dashboards`, `query`, `users`, and `scim` +- supports PAT auth, org API keys, or both on one profile +- uses browser login for PAT setup +- supports keychain-backed secrets on macOS with config-file fallback +- provides `doctor`, `schema`, `exit-codes`, and raw `api call` for agent/runtime integration +- includes an interactive connection creation wizard for supported dialects, with `--file` still available for automation + +## Automation Contract -## Error contract +- Success payloads are written to `stdout`. +- Error payloads are written to `stderr`. +- `--json` is the preferred mode for callers and agents. +- `--plain` provides stable TSV-style output for list-shaped responses. +- `omni exit-codes` prints the stable exit-code and error-code contract. +- `omni schema [command path]` prints machine-readable command metadata. +- `OMNI_ENABLE_COMMANDS` can restrict the allowed top-level command set for embedded/agent use. -- Success payloads are printed to `stdout`. -- Error payloads are printed to `stderr`. -- `--plain` prints stable tab-delimited output for list-style responses. -- In `--json` mode, errors use: +Error shape in `--json` mode: ```json { @@ -109,90 +46,121 @@ omni completion fish > ~/.config/fish/completions/omni.fish } ``` -## Example usage +## Auth Model + +Profiles live in `~/.omni/config.json` by default. + +- `pat`: PAT acquired through browser login +- `org`: org API key entered directly +- `both`: PAT plus org key on one profile + +Runtime behavior: + +- general commands use the profile's `default_auth` +- `admin`, `users`, and `scim` require org auth automatically +- `--auth pat|org` overrides the auth used for the current command +- `--token` and `--token-type` still work as legacy/manual overrides + +PAT flow details are documented in [docs/pat-auth-flow.md](docs/pat-auth-flow.md). + +## Setup + +Interactive setup: ```bash omni setup -omni setup --profile prod --url https://acme.omniapp.co --auth-mode pat --token-store auto -omni setup --non-interactive --profile prod --url https://acme.omniapp.co --auth-mode org --org-key "$OMNI_ORG_KEY" --token-store auto omni setup --profile prod --url https://acme.omniapp.co --auth-mode both --org-key "$OMNI_ORG_KEY" --default-auth pat -omni --no-input setup --profile prod --url https://acme.omniapp.co --auth-mode org --org-key "$OMNI_ORG_KEY" +``` + +Non-interactive setup: + +```bash +omni setup --non-interactive --profile prod --url https://acme.omniapp.co --auth-mode org --org-key "$OMNI_ORG_KEY" --token-store auto omni auth add --name prod --url https://acme.omniapp.co --auth-mode both --org-key "$OMNI_ORG_KEY" --default-auth pat --token-store keychain -omni --auth org documents list --page-size 20 +omni auth use prod +omni auth show --profile prod --json +``` + +Supported environment variables: + +- `OMNI_PROFILE` +- `OMNI_URL` +- `OMNI_AUTH` +- `OMNI_ORG_KEY` +- `OMNI_PAT` for manual override only; normal PAT setup is browser-based +- `OMNI_TOKEN` +- `OMNI_TOKEN_TYPE` +- `OMNI_CONFIG` +- `OMNI_PLAIN` +- `OMNI_NO_INPUT` +- `OMNI_ENABLE_COMMANDS` + +## Flag Parsing + +Global flags can be provided before or after the command path: + +```bash +omni --json documents list +omni documents list --json +``` + +Command-local flags should be placed before positional arguments. For example: + +```bash +omni documents rename --name "Q1 Dashboard" wk_abc123 +omni folders create --scope organization "Team Reports" +omni labels create --homepage true finance +``` + +## Machine-Oriented Examples + +```bash omni schema omni schema documents permissions omni exit-codes --json omni doctor --json -omni --plain documents list --page-size 20 -omni documents list --page-size 20 --json -OMNI_ENABLE_COMMANDS=query,documents omni documents list --page-size 20 -omni completion zsh > ~/.zsh/completions/_omni -omni documents list --page-size 20 -omni documents get wk_abc123 -omni documents create --file document.json -omni documents rename wk_abc123 --name "Executive Dashboard" -omni documents permissions add wk_abc123 --file permits.json -omni models list --name marketing -omni models validate 550e8400-e29b-41d4-a716-446655440000 -omni models topics list 550e8400-e29b-41d4-a716-446655440000 -omni connections list -omni connections create -omni connections create --file connection.json -omni connections dbt update 550e8400-e29b-41d4-a716-446655440000 --file connection-dbt.json -omni connections schedules list 550e8400-e29b-41d4-a716-446655440000 -omni connections environments list -omni folders list --page-size 20 -omni folders create "Team Reports" --scope organization -omni folders permissions get 550e8400-e29b-41d4-a716-446655440000 -omni labels list -omni labels create finance --homepage true -omni schedules list --page-size 20 -omni schedules create --file schedule.json -omni schedules update 550e8400-e29b-41d4-a716-446655440000 -omni schedules recipients add 550e8400-e29b-41d4-a716-446655440000 --file recipients.json -omni schedules trigger 550e8400-e29b-41d4-a716-446655440000 -omni dashboards download wk_abc123 --file dashboard-download.json -omni dashboards filters update wk_abc123 --file dashboard-filters.json -omni agentic submit --file agentic-job.json -omni embed sso generate-session --file embed-session.json -omni unstable documents export wk_abc123 -omni user-attributes list -omni admin users list --count 10 -omni users list-email-only --page-size 20 -omni scim users list --count 20 -omni ai generate-query --model-id 550e8400-e29b-41d4-a716-446655440000 --prompt "Revenue by month" -omni ai workbook --model-id 550e8400-e29b-41d4-a716-446655440000 --prompt "Top 10 customers by revenue" omni api call --method GET --path /api/v1/documents -omni auth whoami omni query run --file query.json --result-type json --wait -omni jobs status 12345 +omni user-attributes list --json +OMNI_ENABLE_COMMANDS=query,documents omni documents list --page-size 20 --json ``` -## Auth model - -- `omni setup` asks what auth to configure: `pat`, `org`, or `both` -- PAT setup uses browser login rather than asking the user to paste a token -- Profiles can store both a PAT and an org key at the same time -- General commands use the profile's `default_auth` -- Org-only commands such as `admin`, `users`, and `scim` automatically use the org key -- `--auth pat|org` forces a specific credential for the current command -- `OMNI_PAT`, `--token`, and `--token-type` are still accepted as manual/legacy overrides +## Command Surface + +Top-level commands: + +- `schema` +- `exit-codes` +- `doctor` +- `completion` +- `setup` +- `auth` +- `documents` +- `models` +- `connections` +- `folders` +- `labels` +- `schedules` +- `dashboards` +- `agentic` +- `embed` +- `unstable` +- `user-attributes` +- `admin` +- `users` +- `scim` +- `ai` +- `api` +- `query` +- `jobs` +- `version` + +High-value subcommands: -See also: - -- `docs/pat-auth-flow.md` - -## Command overview - -- `omni setup` -- `omni schema` -- `omni exit-codes` -- `omni doctor` - `omni auth add|list|remove|use|show|whoami` - `omni documents list|get|create|delete|rename|move|draft create|draft discard|duplicate|favorite add|favorite remove|access list|permissions get|permissions add|permissions update|permissions revoke|permissions settings|label add|label remove|labels bulk-update|queries|transfer-ownership` - `omni models list|get|create|refresh|validate|branch delete|branch merge|cache-reset|topics list|get|update|delete|views list|update|delete|fields create|update|delete|git get|create|update|delete|sync|migrate|content-validator get|replace|yaml get|create|delete` - `omni connections list|create|update|dbt get|dbt update|dbt delete|schedules list|schedules create|schedules get|schedules update|schedules delete|environments list|environments create|environments update|environments delete` - `connections create` supports an interactive wizard or `--file` JSON input - `omni folders list|create|delete|permissions get|permissions add|permissions update|permissions revoke` - `omni labels list|get|create|update|delete` - `omni schedules list|create|get|update|delete|pause|resume|trigger|recipients get|recipients add|recipients remove|transfer-ownership` @@ -210,29 +178,97 @@ See also: - `omni query run` - `omni jobs status` -## Build +The bundled OpenAPI coverage report is tracked in: + +- [docs/endpoint-coverage.md](docs/endpoint-coverage.md) +- [docs/endpoint-coverage.json](docs/endpoint-coverage.json) + +## Connections Wizard + +`omni connections create` can run interactively in a terminal, or accept `--file` JSON for automation. + +Supported interactive dialects: + +- `postgres` +- `redshift` +- `mysql` +- `mariadb` +- `mssql` +- `snowflake` +- `databricks` +- `bigquery` +- `athena` +- `motherduck` +- `clickhouse` +- `exasol` +- `starrocks` +- `trino` -`go` is required locally. +Examples: + +```bash +omni connections create +omni connections create --file connection.json +omni connections update 550e8400-e29b-41d4-a716-446655440000 --file connection-update.json +omni connections environments list +omni connections schedules list 550e8400-e29b-41d4-a716-446655440000 +``` + +## Human Debugging Examples + +These are still useful when developing the CLI, but they are secondary to the machine-facing contract. + +```bash +omni completion zsh > ~/.zsh/completions/_omni +omni documents list --page-size 20 +omni documents get wk_abc123 +omni documents rename --name "Executive Dashboard" wk_abc123 +omni documents permissions add wk_abc123 --file permits.json +omni models list --name marketing +omni folders permissions get 550e8400-e29b-41d4-a716-446655440000 +omni labels create --homepage true finance +omni schedules create --file schedule.json +omni schedules recipients add 550e8400-e29b-41d4-a716-446655440000 --file recipients.json +omni dashboards filters update wk_abc123 --file dashboard-filters.json +omni agentic submit --file agentic-job.json +omni embed sso generate-session --file embed-session.json +omni unstable documents export wk_abc123 +omni users list-email-only --page-size 20 +omni scim users list --count 20 +omni ai generate-query --model-id 550e8400-e29b-41d4-a716-446655440000 --prompt "Revenue by month" +omni jobs status 12345 +``` + +## Repo Layout + +- `cmd/omni`: entrypoint +- `internal/cli`: handwritten command handlers and runtime wiring +- `internal/auth`: auth resolution and profile behavior +- `internal/config`: config load/save and profile format +- `internal/client`: handwritten client wrappers +- `internal/client/gen`: generated OpenAPI client code +- `internal/output`: stdout/stderr and plain/json formatting helpers +- `internal/secret`: keychain/config credential storage abstraction +- `api/openapi.json`: checked-in Omni API spec +- `scripts/update_openapi.sh`: fetch and normalize an Omni OpenAPI spec +- `scripts/generate_client.sh`: regenerate the typed client + +## Build And Release ```bash make build make test +make coverage-report ``` -## Refresh OpenAPI Client +Refresh the API client: ```bash ./scripts/update_openapi.sh https://your-instance.omniapp.co/openapi.json go generate ./internal/client/gen -make coverage-report ``` -Coverage outputs: - -- `docs/endpoint-coverage.md` -- `docs/endpoint-coverage.json` - -## Release +Build release artifacts locally: ```bash goreleaser release --snapshot --clean From 3ffc2f6f6aafd2a7c48313175fd63a8dc7b6df07 Mon Sep 17 00:00:00 2001 From: hawkfry Date: Sun, 15 Mar 2026 23:05:24 +0000 Subject: [PATCH 3/3] test: update connection tests with example values for improved clarity and consistency --- internal/cli/connections_test.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/cli/connections_test.go b/internal/cli/connections_test.go index 05a3a29..78b1368 100644 --- a/internal/cli/connections_test.go +++ b/internal/cli/connections_test.go @@ -18,7 +18,7 @@ import ( func TestRunConnectionsCreateWithFile(t *testing.T) { tmp := t.TempDir() bodyPath := filepath.Join(tmp, "connection.json") - if err := os.WriteFile(bodyPath, []byte(`{"dialect":"postgres","name":"Coverage Postgres","passwordUnencrypted":"secret"}`), 0o600); err != nil { + if err := os.WriteFile(bodyPath, []byte(`{"dialect":"postgres","name":"Coverage Postgres","passwordUnencrypted":"example-test-password-not-a-secret"}`), 0o600); err != nil { t.Fatalf("write connection body: %v", err) } @@ -96,7 +96,7 @@ func TestRunConnectionsCreateInteractivePostgresWizard(t *testing.T) { reader := bufio.NewReader(strings.NewReader(strings.Join([]string{ "", "Coverage Postgres", - "db.example.internal", + "db.example.invalid", "", "analytics", "omni", @@ -111,7 +111,7 @@ func TestRunConnectionsCreateInteractivePostgresWizard(t *testing.T) { stdout, stderr, exit := captureRuntimeIO(t, func() int { return runConnectionsCreateWithPrompts(rt, nil, true, reader, func(_ *bufio.Reader, _ string) (string, error) { - return "top-secret", nil + return "example-test-password-not-a-secret", nil }) }) if exit != 0 { @@ -129,7 +129,7 @@ func TestRunConnectionsCreateInteractivePostgresWizard(t *testing.T) { if gotBody.Name != "Coverage Postgres" { t.Fatalf("expected name to be preserved, got %q", gotBody.Name) } - if gotBody.Host == nil || *gotBody.Host != "db.example.internal" { + if gotBody.Host == nil || *gotBody.Host != "db.example.invalid" { t.Fatalf("expected host to be set, got %#v", gotBody.Host) } if gotBody.Port == nil || *gotBody.Port != 5432 { @@ -141,7 +141,7 @@ func TestRunConnectionsCreateInteractivePostgresWizard(t *testing.T) { if gotBody.Username == nil || *gotBody.Username != "omni" { t.Fatalf("expected username to be set, got %#v", gotBody.Username) } - if gotBody.PasswordUnencrypted != "top-secret" { + if gotBody.PasswordUnencrypted != "example-test-password-not-a-secret" { t.Fatalf("expected password to be forwarded, got %q", gotBody.PasswordUnencrypted) } if gotBody.BaseRole == nil || *gotBody.BaseRole != gen.QUERIER { @@ -189,7 +189,7 @@ func TestPromptConnectionCreatePayloadValidation(t *testing.T) { input: strings.Join([]string{ "postgres", "Coverage Postgres", - "db.example.internal", + "db.example.invalid", "zero", }, "\n") + "\n", want: "port must be a positive integer", @@ -199,13 +199,13 @@ func TestPromptConnectionCreatePayloadValidation(t *testing.T) { input: strings.Join([]string{ "postgres", "Coverage Postgres", - "db.example.internal", + "db.example.invalid", "5432", "analytics", "omni", "not-a-role", }, "\n") + "\n", - secret: "top-secret", + secret: "example-test-password-not-a-secret", want: `invalid base role "not-a-role"`, }, } @@ -228,7 +228,7 @@ func TestPromptConnectionCreatePayloadValidation(t *testing.T) { func TestPromptConnectionCreatePayloadBigQueryUsesServiceAccountDefaults(t *testing.T) { tmp := t.TempDir() serviceAccountPath := filepath.Join(tmp, "service-account.json") - serviceAccount := `{"project_id":"coverage-project","client_email":"svc@coverage-project.iam.gserviceaccount.com"}` + serviceAccount := `{"project_id":"example-project-not-real","client_email":"svc@example-project-not-real.iam.gserviceaccount.invalid"}` if err := os.WriteFile(serviceAccountPath, []byte(serviceAccount), 0o600); err != nil { t.Fatalf("write service account file: %v", err) } @@ -266,10 +266,10 @@ func TestPromptConnectionCreatePayloadBigQueryUsesServiceAccountDefaults(t *test if got["dialect"] != "bigquery" { t.Fatalf("expected bigquery dialect, got %#v", got["dialect"]) } - if got["database"] != "coverage-project" { + if got["database"] != "example-project-not-real" { t.Fatalf("expected project ID default, got %#v", got["database"]) } - if got["username"] != "svc@coverage-project.iam.gserviceaccount.com" { + if got["username"] != "svc@example-project-not-real.iam.gserviceaccount.invalid" { t.Fatalf("expected client email default, got %#v", got["username"]) } if got["region"] != "us" {