sodabase 0.1.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,28 @@ import { join } from "node:path";
8
8
  import { emailOtpStart, emailOtpVerify, loopbackSignIn, resolveGoTrueConfig } from "./gotrueAuth.js";
9
9
  import { ApiError, } from "./types.js";
10
10
  export const MCP_URL = "https://sodabase.io/mcp";
11
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
11
+ /** The trust-advisor skill repo, resolved by the `skills` CLI (owner/repo on its default branch). */
12
+ export const SKILL_REF = "sodabase/agent-skills";
13
+ /** An error thrown when `connect()`'s poll is aborted (the user left the connect screen). */
14
+ const abortedError = () => new ApiError("connect aborted", 499, "aborted");
15
+ /** Resolve after `ms`, or reject immediately if `signal` aborts (so leaving the screen doesn't wait).
16
+ * The abort listener is removed when the timer wins — otherwise connect()'s per-poll calls would pile
17
+ * up listeners on the same signal and trip Node's MaxListenersExceededWarning (which corrupts the TUI). */
18
+ function sleepAbortable(ms, signal) {
19
+ return new Promise((resolve, reject) => {
20
+ if (signal?.aborted)
21
+ return reject(abortedError());
22
+ const onAbort = () => {
23
+ clearTimeout(t);
24
+ reject(abortedError());
25
+ };
26
+ const t = setTimeout(() => {
27
+ signal?.removeEventListener("abort", onAbort);
28
+ resolve();
29
+ }, ms);
30
+ signal?.addEventListener("abort", onAbort, { once: true });
31
+ });
32
+ }
12
33
  /** Open a URL in the user's default browser (best-effort; the URL is also shown as text). */
13
34
  function openUrl(url) {
14
35
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
@@ -52,28 +73,34 @@ export class SodabaseClient {
52
73
  // ── Local: detect the Supabase project from the cwd ─────────────────────────
53
74
  async detectProject() {
54
75
  const cwd = process.cwd();
55
- let projectRef = "unknown";
56
76
  const configToml = join(cwd, "supabase", "config.toml");
57
- if (existsSync(configToml)) {
58
- const m = /project_id\s*=\s*"([^"]+)"/.exec(readFileSync(configToml, "utf8"));
77
+ const hasConfigToml = existsSync(configToml);
78
+ let projectRef = "";
79
+ if (hasConfigToml) {
80
+ // project_id may be single- or double-quoted
81
+ const m = /project_id\s*=\s*["']([^"']+)["']/.exec(readFileSync(configToml, "utf8"));
59
82
  if (m?.[1])
60
83
  projectRef = m[1];
61
84
  }
62
- let framework = "unknown";
63
85
  const pkg = join(cwd, "package.json");
64
- if (existsSync(pkg)) {
86
+ const hasPackageJson = existsSync(pkg);
87
+ let framework = "";
88
+ if (hasPackageJson) {
65
89
  try {
66
- const deps = JSON.parse(readFileSync(pkg, "utf8"));
67
- if (deps.dependencies?.["@supabase/supabase-js"])
90
+ const json = JSON.parse(readFileSync(pkg, "utf8"));
91
+ // Scan both dependency sets — supabase-js often lives under devDependencies, and monorepo
92
+ // roots vary. (Framework is display-only; it never drives onboarding.)
93
+ const all = { ...json.devDependencies, ...json.dependencies };
94
+ if (all["@supabase/supabase-js"])
68
95
  framework = "@supabase/supabase-js";
69
- if (deps.dependencies?.next)
96
+ if (all.next)
70
97
  framework = "Next.js + @supabase/supabase-js";
71
98
  }
72
99
  catch {
73
100
  /* a malformed package.json in the cwd must not crash boot — detection is best-effort */
74
101
  }
75
102
  }
76
- return { directory: cwd, framework, projectRef, database: "Supabase Postgres" };
103
+ return { directory: cwd, framework, projectRef, hasPackageJson, hasConfigToml };
77
104
  }
78
105
  // ── Leg 2: Supabase connect via the HOSTED handback (Supabase requires an HTTPS public-host
79
106
  // redirect, so no loopback). start(redirect_uri = hosted handback) → browser authorizes →
@@ -99,7 +126,9 @@ export class SodabaseClient {
99
126
  ...(r.already_connected ? { alreadyConnected: true } : {}),
100
127
  };
101
128
  }
102
- async connect() {
129
+ async connect(signal) {
130
+ if (signal?.aborted)
131
+ throw abortedError();
103
132
  const { authorizeUrl } = await this.startConnect(this.handbackUrl());
104
133
  const state = new URL(authorizeUrl).searchParams.get("state");
105
134
  if (!state)
@@ -107,9 +136,13 @@ export class SodabaseClient {
107
136
  openUrl(authorizeUrl);
108
137
  const deadline = Date.now() + 5 * 60_000; // give the user time to approve in the browser
109
138
  // Serialize polls (await each before the next) per the cli-complete polling contract — overlapping
110
- // in-flight polls can race the take-before-exchange window.
139
+ // in-flight polls can race the take-before-exchange window. The signal stops the loop when the user
140
+ // leaves the connect screen, so an abandoned authorize doesn't keep polling (and a re-entry can't
141
+ // start a competing loop).
111
142
  let seenPending = false;
112
143
  for (;;) {
144
+ if (signal?.aborted)
145
+ throw abortedError();
113
146
  let r;
114
147
  try {
115
148
  r = await this.cliComplete(state);
@@ -128,7 +161,7 @@ export class SodabaseClient {
128
161
  if (Date.now() > deadline) {
129
162
  throw new ApiError("timed out waiting for Supabase authorization in the browser", 408, "timeout");
130
163
  }
131
- await sleep(2000);
164
+ await sleepAbortable(2000, signal);
132
165
  }
133
166
  }
134
167
  async listProjects(connectionId) {
@@ -167,6 +200,17 @@ export class SodabaseClient {
167
200
  async jobStatus(jobId) {
168
201
  return this.get(`/onboarding/jobs/${encodeURIComponent(jobId)}`);
169
202
  }
203
+ // ── Manage: a project's tables + per-table watch toggle (same endpoints the dashboard uses) ──
204
+ async projectDatasets(projectRef) {
205
+ const rows = await this.get(`/projects/${encodeURIComponent(projectRef)}/datasets`);
206
+ // Be defensive about the body shape — a non-array (empty-body {} / error envelope) must not throw
207
+ // `.map is not a function` up into the screen.
208
+ return Array.isArray(rows) ? rows.map((d) => ({ id: d.id, name: d.name, monitored: d.monitored })) : [];
209
+ }
210
+ async toggleDataset(projectRef, datasetId, enabled) {
211
+ const r = await this.post(`/projects/${encodeURIComponent(projectRef)}/datasets/${encodeURIComponent(datasetId)}/monitor`, { enabled });
212
+ return { monitored: r.monitored, needsReauth: r.needs_reauth };
213
+ }
170
214
  // ── Scope: relevance (onboard-then-adjust; operates on monitor ids) ──────────
171
215
  async proposals() {
172
216
  return this.get("/relevance/proposals");
@@ -201,8 +245,25 @@ export class SodabaseClient {
201
245
  };
202
246
  return { command, wrote: agents.map((a) => ({ agent: a, path: paths[a] ?? "~/.config/<agent>" })) };
203
247
  }
204
- // Note: no scanReport/illustrativeFindings — the data-trust surface is MCP-only, there is
205
- // no /api/v1 route returning scan findings. The Findings screen shows status + a link.
248
+ // ── Local: consented in-flow trust-advisor skill install via the `skills` CLI ──
249
+ async installSkill(agents) {
250
+ // Same non-TTY reasoning as installMcp: the leading `-y` skips npx's first-run prompt; the trailing
251
+ // `-y` (skills' --yes) skips ALL of its confirmation prompts (incl. the symlink-vs-copy method choice),
252
+ // which it would otherwise block on without a TTY. `-g -a <agent>` mirrors the MCP targets.
253
+ const args = ["-y", "skills", "add", SKILL_REF, "-g", ...agents.flatMap((a) => ["-a", a]), "-y"];
254
+ const command = `npx ${args.join(" ")}`;
255
+ await new Promise((resolve, reject) => {
256
+ let stderr = "";
257
+ // On Windows npx is `npx.cmd`, only resolvable via the shell (args are a fixed constant list — no injection).
258
+ const child = spawn("npx", args, { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32" });
259
+ child.stderr?.on("data", (d) => (stderr += String(d)));
260
+ child.on("error", reject);
261
+ child.on("exit", (code) => code === 0
262
+ ? resolve()
263
+ : reject(new Error(`skills exited ${code}${stderr ? `: ${stderr.trim().split("\n").slice(-2).join("; ")}` : ""}`)));
264
+ });
265
+ return { command };
266
+ }
206
267
  // ── low-level helpers ───────────────────────────────────────────────────────
207
268
  authHeaders() {
208
269
  return this.bearer ? { authorization: `Bearer ${this.bearer}` } : {};
@@ -14,9 +14,23 @@ const JOB_STEPS = [
14
14
  export class FakeClient {
15
15
  fast;
16
16
  jobIdx = 0;
17
+ // Per-project demo tables with a MIX of watched/unwatched state, so toggling shows real changes.
18
+ datasets = {};
17
19
  constructor(opts = {}) {
18
20
  this.fast = opts.fast ?? false;
19
21
  }
22
+ datasetsFor(ref) {
23
+ if (!this.datasets[ref]) {
24
+ this.datasets[ref] = [
25
+ { id: "ds_orders", name: "public.orders", monitored: true },
26
+ { id: "ds_payments", name: "public.payments", monitored: true },
27
+ { id: "ds_events", name: "public.events", monitored: true },
28
+ { id: "ds_users", name: "public.users", monitored: false },
29
+ { id: "ds_feature_flags", name: "public.feature_flags", monitored: false },
30
+ ];
31
+ }
32
+ return this.datasets[ref];
33
+ }
20
34
  tick(ms) {
21
35
  return sleep(Math.round(ms * (this.fast ? 0.12 : 1)));
22
36
  }
@@ -26,7 +40,8 @@ export class FakeClient {
26
40
  directory: "project-supabase",
27
41
  framework: "Next.js + @supabase/supabase-js",
28
42
  projectRef: "supabase-demo",
29
- database: "Postgres 17 · Supavisor pooler reachable",
43
+ hasPackageJson: true,
44
+ hasConfigToml: true,
30
45
  };
31
46
  }
32
47
  async signIn(_provider) {
@@ -44,9 +59,11 @@ export class FakeClient {
44
59
  setBearer() {
45
60
  /* no-op in demo */
46
61
  }
47
- async connect() {
62
+ async connect(signal) {
48
63
  // No real browser in demo — just simulate the authorize + callback round-trip.
49
64
  await this.tick(900);
65
+ if (signal?.aborted)
66
+ throw new Error("connect aborted");
50
67
  return { connectionId: "conn_demo" };
51
68
  }
52
69
  async listProjects(_connectionId) {
@@ -87,6 +104,17 @@ export class FakeClient {
87
104
  error: null,
88
105
  };
89
106
  }
107
+ async projectDatasets(ref) {
108
+ await this.tick(400);
109
+ return this.datasetsFor(ref).map((d) => ({ ...d }));
110
+ }
111
+ async toggleDataset(ref, datasetId, enabled) {
112
+ await this.tick(300);
113
+ const d = this.datasetsFor(ref).find((x) => x.id === datasetId);
114
+ if (d)
115
+ d.monitored = enabled;
116
+ return { monitored: enabled, needsReauth: false };
117
+ }
90
118
  async proposals() {
91
119
  await this.tick(500);
92
120
  return {
@@ -119,12 +147,8 @@ export class FakeClient {
119
147
  wrote: agents.map((a) => ({ agent: a, path: paths[a] ?? "~/.config/<agent>" })),
120
148
  };
121
149
  }
122
- async illustrativeFindings() {
150
+ async installSkill(agents) {
123
151
  await this.tick(500);
124
- return [
125
- { column: "public.orders.customer_email", family: "missing", detail: "3.2% missing on last-24h rows", severity: "bad" },
126
- { column: "public.payments.idempotency_key", family: "duplicate", detail: "11 duplicate keys in the last hour", severity: "warn" },
127
- { column: "public.events", family: "healthy", detail: "Flowing on schedule — within baseline", severity: "ok" },
128
- ];
152
+ return { command: `npx skills add sodabase/agent-skills -g ${agents.map((a) => "-a " + a).join(" ")}` };
129
153
  }
130
154
  }
@@ -22,6 +22,25 @@ const DEFAULT_SUPABASE_URL = "https://jxbfyuzqizsenxekupte.supabase.co";
22
22
  const DEFAULT_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imp4YmZ5dXpxaXpzZW54ZWt1cHRlIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODkzNzQzNDUsImV4cCI6MjEwNDk1MDM0NX0.ahdAbYaIRZXr8awIBG-W7soWLahtLISSrIzl243Xuas";
23
23
  export const LOOPBACK_PORT = 8976;
24
24
  export const LOOPBACK_REDIRECT = `http://127.0.0.1:${LOOPBACK_PORT}/callback`;
25
+ // Branded sign-in result page served on the loopback -- the browser half of `npx sodabase`. Matches the
26
+ // connect-handback housestyle (IBM Plex, the dot-matrix mark, green = Sodabase, light + dark). Sign-in is
27
+ // only authentication -- nothing is connected yet -- so the mark holds still here; the moving "watching"
28
+ // scan is reserved for the connect handback, where the data connection is actually live.
29
+ const CALLBACK_MARK = '<circle cx="8.27" cy="1.2" r=".48"/><circle cx="9.47" cy="1.2" r=".48"/><circle cx="10.67" cy="1.2" r=".48"/><circle cx="7.07" cy="2.4" r=".48"/><circle cx="8.27" cy="2.4" r=".48"/><circle cx="9.47" cy="2.4" r=".48"/><circle cx="10.67" cy="2.4" r=".48"/><circle cx="11.87" cy="2.4" r=".48"/><circle cx="5.87" cy="3.6" r=".48"/><circle cx="7.07" cy="3.6" r=".48"/><circle cx="8.27" cy="3.6" r=".48"/><circle cx="9.47" cy="3.6" r=".48"/><circle cx="10.67" cy="3.6" r=".48"/><circle cx="11.87" cy="3.6" r=".48"/><circle cx="13.07" cy="3.6" r=".48"/><circle cx="5.87" cy="4.8" r=".48"/><circle cx="7.07" cy="4.8" r=".48"/><circle cx="8.27" cy="4.8" r=".48"/><circle cx="9.47" cy="4.8" r=".48"/><circle cx="10.67" cy="4.8" r=".48"/><circle cx="11.87" cy="4.8" r=".48"/><circle cx="13.07" cy="4.8" r=".48"/><circle cx="5.87" cy="6.0" r=".48"/><circle cx="7.07" cy="6.0" r=".48"/><circle cx="8.27" cy="6.0" r=".48"/><circle cx="9.47" cy="6.0" r=".48"/><circle cx="10.67" cy="6.0" r=".48"/><circle cx="11.87" cy="6.0" r=".48"/><circle cx="13.07" cy="6.0" r=".48"/><circle cx="7.07" cy="7.2" r=".48"/><circle cx="8.27" cy="7.2" r=".48"/><circle cx="9.47" cy="7.2" r=".48"/><circle cx="10.67" cy="7.2" r=".48"/><circle cx="11.87" cy="7.2" r=".48"/><circle cx="8.27" cy="8.4" r=".48"/><circle cx="9.47" cy="8.4" r=".48"/><circle cx="10.67" cy="8.4" r=".48"/><circle cx="8.27" cy="1.2" r=".48"/><circle cx="9.47" cy="1.2" r=".48"/><circle cx="10.67" cy="1.2" r=".48"/><circle cx="7.07" cy="2.4" r=".48"/><circle cx="8.27" cy="2.4" r=".48"/><circle cx="9.47" cy="2.4" r=".48"/><circle cx="10.67" cy="2.4" r=".48"/><circle cx="11.87" cy="2.4" r=".48"/><circle cx="5.87" cy="3.6" r=".48"/><circle cx="7.07" cy="3.6" r=".48"/><circle cx="8.27" cy="3.6" r=".48"/><circle cx="9.47" cy="3.6" r=".48"/><circle cx="10.67" cy="3.6" r=".48"/><circle cx="11.87" cy="3.6" r=".48"/><circle cx="13.07" cy="3.6" r=".48"/><circle cx="5.87" cy="4.8" r=".48"/><circle cx="7.07" cy="4.8" r=".48"/><circle cx="8.27" cy="4.8" r=".48"/><circle cx="9.47" cy="4.8" r=".48"/><circle cx="10.67" cy="4.8" r=".48"/><circle cx="11.87" cy="4.8" r=".48"/><circle cx="13.07" cy="4.8" r=".48"/><circle cx="5.87" cy="6.0" r=".48"/><circle cx="7.07" cy="6.0" r=".48"/><circle cx="8.27" cy="6.0" r=".48"/><circle cx="9.47" cy="6.0" r=".48"/><circle cx="10.67" cy="6.0" r=".48"/><circle cx="11.87" cy="6.0" r=".48"/><circle cx="13.07" cy="6.0" r=".48"/><circle cx="7.07" cy="7.2" r=".48"/><circle cx="8.27" cy="7.2" r=".48"/><circle cx="9.47" cy="7.2" r=".48"/><circle cx="14.8" cy="12.4" r=".48"/><circle cx="16.0" cy="12.4" r=".48"/><circle cx="17.2" cy="12.4" r=".48"/><circle cx="13.6" cy="13.6" r=".48"/><circle cx="14.8" cy="13.6" r=".48"/><circle cx="16.0" cy="13.6" r=".48"/><circle cx="17.2" cy="13.6" r=".48"/><circle cx="18.4" cy="13.6" r=".48"/><circle cx="12.4" cy="14.8" r=".48"/><circle cx="13.6" cy="14.8" r=".48"/><circle cx="14.8" cy="14.8" r=".48"/><circle cx="16.0" cy="14.8" r=".48"/><circle cx="17.2" cy="14.8" r=".48"/><circle cx="18.4" cy="14.8" r=".48"/><circle cx="19.6" cy="14.8" r=".48"/><circle cx="12.4" cy="16.0" r=".48"/><circle cx="13.6" cy="16.0" r=".48"/><circle cx="14.8" cy="16.0" r=".48"/><circle cx="16.0" cy="16.0" r=".48"/><circle cx="17.2" cy="16.0" r=".48"/><circle cx="18.4" cy="16.0" r=".48"/><circle cx="19.6" cy="16.0" r=".48"/><circle cx="12.4" cy="17.2" r=".48"/><circle cx="13.6" cy="17.2" r=".48"/><circle cx="14.8" cy="17.2" r=".48"/><circle cx="16.0" cy="17.2" r=".48"/><circle cx="17.2" cy="17.2" r=".48"/><circle cx="18.4" cy="17.2" r=".48"/><circle cx="19.6" cy="17.2" r=".48"/><circle cx="13.6" cy="18.4" r=".48"/><circle cx="14.8" cy="18.4" r=".48"/><circle cx="16.0" cy="18.4" r=".48"/><circle cx="17.2" cy="18.4" r=".48"/><circle cx="18.4" cy="18.4" r=".48"/><circle cx="14.8" cy="19.6" r=".48"/><circle cx="16.0" cy="19.6" r=".48"/><circle cx="17.2" cy="19.6" r=".48"/><circle cx="14.8" cy="12.4" r=".48"/><circle cx="16.0" cy="12.4" r=".48"/><circle cx="17.2" cy="12.4" r=".48"/><circle cx="13.6" cy="13.6" r=".48"/><circle cx="14.8" cy="13.6" r=".48"/><circle cx="16.0" cy="13.6" r=".48"/><circle cx="17.2" cy="13.6" r=".48"/><circle cx="18.4" cy="13.6" r=".48"/><circle cx="12.4" cy="14.8" r=".48"/><circle cx="13.6" cy="14.8" r=".48"/><circle cx="14.8" cy="14.8" r=".48"/><circle cx="16.0" cy="14.8" r=".48"/><circle cx="17.2" cy="14.8" r=".48"/><circle cx="18.4" cy="14.8" r=".48"/><circle cx="19.6" cy="14.8" r=".48"/><circle cx="12.4" cy="16.0" r=".48"/><circle cx="13.6" cy="16.0" r=".48"/><circle cx="14.8" cy="16.0" r=".48"/><circle cx="16.0" cy="16.0" r=".48"/><circle cx="17.2" cy="16.0" r=".48"/><circle cx="18.4" cy="16.0" r=".48"/><circle cx="19.6" cy="16.0" r=".48"/><circle cx="12.4" cy="17.2" r=".48"/><circle cx="13.6" cy="17.2" r=".48"/><circle cx="14.8" cy="17.2" r=".48"/><circle cx="16.0" cy="17.2" r=".48"/><circle cx="17.2" cy="17.2" r=".48"/><circle cx="18.4" cy="17.2" r=".48"/><circle cx="19.6" cy="17.2" r=".48"/><circle cx="13.6" cy="18.4" r=".48"/><circle cx="14.8" cy="18.4" r=".48"/><circle cx="16.0" cy="18.4" r=".48"/><circle cx="21.33" cy="23.6" r=".48"/><circle cx="22.53" cy="23.6" r=".48"/><circle cx="23.73" cy="23.6" r=".48"/><circle cx="20.13" cy="24.8" r=".48"/><circle cx="21.33" cy="24.8" r=".48"/><circle cx="22.53" cy="24.8" r=".48"/><circle cx="23.73" cy="24.8" r=".48"/><circle cx="24.93" cy="24.8" r=".48"/><circle cx="18.93" cy="26.0" r=".48"/><circle cx="20.13" cy="26.0" r=".48"/><circle cx="21.33" cy="26.0" r=".48"/><circle cx="22.53" cy="26.0" r=".48"/><circle cx="23.73" cy="26.0" r=".48"/><circle cx="24.93" cy="26.0" r=".48"/><circle cx="26.13" cy="26.0" r=".48"/><circle cx="18.93" cy="27.2" r=".48"/><circle cx="20.13" cy="27.2" r=".48"/><circle cx="21.33" cy="27.2" r=".48"/><circle cx="22.53" cy="27.2" r=".48"/><circle cx="23.73" cy="27.2" r=".48"/><circle cx="24.93" cy="27.2" r=".48"/><circle cx="26.13" cy="27.2" r=".48"/><circle cx="18.93" cy="28.4" r=".48"/><circle cx="20.13" cy="28.4" r=".48"/><circle cx="21.33" cy="28.4" r=".48"/><circle cx="22.53" cy="28.4" r=".48"/><circle cx="23.73" cy="28.4" r=".48"/><circle cx="24.93" cy="28.4" r=".48"/><circle cx="26.13" cy="28.4" r=".48"/><circle cx="20.13" cy="29.6" r=".48"/><circle cx="21.33" cy="29.6" r=".48"/><circle cx="22.53" cy="29.6" r=".48"/><circle cx="23.73" cy="29.6" r=".48"/><circle cx="24.93" cy="29.6" r=".48"/><circle cx="21.33" cy="30.8" r=".48"/><circle cx="22.53" cy="30.8" r=".48"/><circle cx="23.73" cy="30.8" r=".48"/><circle cx="21.33" cy="23.6" r=".48"/><circle cx="22.53" cy="23.6" r=".48"/><circle cx="23.73" cy="23.6" r=".48"/><circle cx="20.13" cy="24.8" r=".48"/><circle cx="21.33" cy="24.8" r=".48"/><circle cx="22.53" cy="24.8" r=".48"/><circle cx="23.73" cy="24.8" r=".48"/><circle cx="24.93" cy="24.8" r=".48"/><circle cx="18.93" cy="26.0" r=".48"/><circle cx="20.13" cy="26.0" r=".48"/><circle cx="21.33" cy="26.0" r=".48"/><circle cx="22.53" cy="26.0" r=".48"/><circle cx="23.73" cy="26.0" r=".48"/><circle cx="24.93" cy="26.0" r=".48"/><circle cx="26.13" cy="26.0" r=".48"/><circle cx="18.93" cy="27.2" r=".48"/><circle cx="20.13" cy="27.2" r=".48"/><circle cx="21.33" cy="27.2" r=".48"/><circle cx="22.53" cy="27.2" r=".48"/><circle cx="23.73" cy="27.2" r=".48"/><circle cx="24.93" cy="27.2" r=".48"/><circle cx="26.13" cy="27.2" r=".48"/><circle cx="18.93" cy="28.4" r=".48"/><circle cx="20.13" cy="28.4" r=".48"/><circle cx="21.33" cy="28.4" r=".48"/><circle cx="22.53" cy="28.4" r=".48"/><circle cx="23.73" cy="28.4" r=".48"/><circle cx="24.93" cy="28.4" r=".48"/><circle cx="26.13" cy="28.4" r=".48"/><circle cx="20.13" cy="29.6" r=".48"/><circle cx="21.33" cy="29.6" r=".48"/><circle cx="22.53" cy="29.6" r=".48"/>';
30
+ const CALLBACK_CSS = ':root{--bg:#f7f7f7;--ink:#0b0b0b;--muted:#6b6b6b;--green:#3CDC97;--accent:#ffc800;color-scheme:light dark}@media(prefers-color-scheme:dark){:root{--bg:#0b0b0b;--ink:#f5f5f5;--muted:#a3a3a3}}*{box-sizing:border-box}html,body{margin:0}body{min-height:100vh;min-height:100svh;display:grid;place-items:center;padding:24px 16px;font-family:"IBM Plex Sans",system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:var(--ink);background:var(--bg);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}::selection{background:var(--accent);color:#0b0b0b}.stage{display:flex;flex-direction:column;align-items:center;text-align:center;gap:16px;max-width:30rem;animation:rise .45s cubic-bezier(.23,1,.32,1) both}.mark{width:84px;height:84px;display:block}.mark circle{fill:var(--green)}.mark.muted circle{fill:var(--muted);opacity:.72}h1{margin:2px 0 0;font-size:24px;line-height:30px;font-weight:600;letter-spacing:-.02em}.lede{margin:4px auto 0;max-width:34ch;font-size:15px;line-height:22px;color:var(--muted)}@media(prefers-reduced-motion:no-preference){.mark.scan circle{transform-box:fill-box;transform-origin:center;animation:ob-scan 2.1s cubic-bezier(.23,1,.32,1) infinite;animation-delay:calc(var(--t,0) * -2.1s)}}@media(prefers-reduced-motion:reduce){.mark.scan circle{animation:ob-breathe 2.4s ease-in-out infinite}.stage{animation:none}}@keyframes rise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}@keyframes ob-scan{0%{opacity:.18;transform:scale(1)}16%{opacity:1;transform:scale(1.28)}42%{opacity:.18;transform:scale(1)}100%{opacity:.18;transform:scale(1)}}@keyframes ob-breathe{0%,100%{opacity:.55}50%{opacity:.95}}';
31
+ const HTML_ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
32
+ function escapeHtml(s) {
33
+ return s.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c] ?? c);
34
+ }
35
+ /** The page served back after the OAuth redirect: signed-in (green mark) or a surfaced error (muted mark). */
36
+ function callbackPage(ok, message) {
37
+ return ("<!doctype html><html lang=en><head><meta charset=utf-8>" +
38
+ '<meta name=viewport content="width=device-width,initial-scale=1">' +
39
+ `<title>Sodabase</title><style>${CALLBACK_CSS}</style></head>` +
40
+ `<body><main class=stage><svg class="mark${ok ? "" : " muted"}" viewBox="0 0 32 32" aria-hidden="true">${CALLBACK_MARK}</svg>` +
41
+ `<h1>${ok ? "You\u2019re signed in" : "Sign-in didn\u2019t finish"}</h1>` +
42
+ `<p class=lede>${message}</p></main></body></html>`);
43
+ }
25
44
  const b64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
26
45
  function openUrl(url) {
27
46
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
@@ -80,9 +99,13 @@ export async function loopbackSignIn(cfg = resolveGoTrueConfig(), opts = {}) {
80
99
  res.end();
81
100
  return;
82
101
  }
83
- // Ignore any callback that isn't ours (missing/mismatched state) — don't let it resolve or reject; keep
84
- // waiting for the real redirect (or the timeout).
85
- if (u.searchParams.get("state") !== state) {
102
+ // Supabase's PKCE redirect does NOT echo our `state` back, so we can't require it — PKCE
103
+ // (code_challenge/verifier) is the real anti-injection guarantee: an injected code can't be
104
+ // exchanged without our verifier, which never leaves this process. We still reject a callback
105
+ // that echoes a DIFFERENT state (a stray hit from another in-flight flow); a missing state is
106
+ // the normal Supabase case and must be accepted, or sign-in would 404 the real redirect and hang.
107
+ const returnedState = u.searchParams.get("state");
108
+ if (returnedState !== null && returnedState !== state) {
86
109
  res.writeHead(404);
87
110
  res.end();
88
111
  return;
@@ -90,9 +113,10 @@ export async function loopbackSignIn(cfg = resolveGoTrueConfig(), opts = {}) {
90
113
  const c = u.searchParams.get("code");
91
114
  const err = u.searchParams.get("error_description") || u.searchParams.get("error");
92
115
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
93
- res.end(`<!doctype html><meta charset="utf-8"><body style="font-family:system-ui;padding:3rem;text-align:center">` +
94
- `<h2>${c ? "Signed in ✓" : "Sign-in failed"}</h2>` +
95
- `<p>${c ? "You can close this tab and return to your terminal." : err || "No code returned."}</p></body>`);
116
+ const ok = Boolean(c);
117
+ res.end(callbackPage(ok, ok
118
+ ? "Head back to your terminal to pick up where you left off."
119
+ : escapeHtml(err || "Sign-in was cancelled, or no code came back. Head back to your terminal and try again.")));
96
120
  clearTimeout(timer); // always clear so the process doesn't linger on the 3-min timer after sign-in
97
121
  server.close();
98
122
  if (c)
package/dist/app.js CHANGED
@@ -1,47 +1,98 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Box } from "ink";
3
- import { useCallback, useState } from "react";
4
- import { clearProgress, saveProgress } from "./config/flowState.js";
5
- import { AgentView, BootDetect, BrandBar, Connect, Findings, McpInstall, Report, ScopeAdjust, SignIn, WizardProvider, } from "./ui.js";
6
- // Ordered flow. Names are the resume keys (index-independent).
7
- const PHASES = [
8
- { name: "boot", Comp: BootDetect },
9
- { name: "signin", Comp: SignIn },
10
- { name: "connect", Comp: Connect },
11
- { name: "agent", Comp: AgentView },
12
- { name: "scope", Comp: ScopeAdjust },
13
- { name: "findings", Comp: Findings },
14
- { name: "mcp", Comp: McpInstall },
15
- { name: "report", Comp: Report },
16
- ];
17
- export function App({ services, fast, interactive, signedIn, demo, startPhase, initialCtx }) {
18
- const startIndex = Math.max(0, startPhase ? PHASES.findIndex((p) => p.name === startPhase) : 0);
19
- const [phase, setPhase] = useState(startIndex === -1 ? 0 : startIndex);
20
- const [ctx, setCtx] = useState(initialCtx ?? {});
2
+ import { Box, useApp, useInput } from "ink";
3
+ import { useCallback, useRef, useState } from "react";
4
+ import { AgentView, BrandBar, Connect, Home, ManageProjects, ManageTables, McpInstall, ScopeAdjust, SignIn, WizardProvider, } from "./ui.js";
5
+ // The screens, by name. Unlike the old linear wizard, navigation is a hub: sign-in lands on `home`
6
+ // (the trust report + action menu), and each action returns there when it finishes.
7
+ const SCREENS = {
8
+ signin: SignIn, // combined detect + sign-in
9
+ home: Home, // trust report + hub menu
10
+ manageprojects: ManageProjects, // pick a watched project, or onboard a new one
11
+ managetables: ManageTables, // watch/unwatch a project's tables
12
+ connect: Connect, // pick a project to watch (onboarding a new one)
13
+ agent: AgentView, // server-side provisioning job (new projects only)
14
+ scope: ScopeAdjust, // choose which tables/monitors run
15
+ mcp: McpInstall, // install the MCP for a coding agent
16
+ };
17
+ /** Where a screen goes when it finishes with no explicit target. `null` = terminal (exit).
18
+ * The hub menu on `home` navigates with an explicit `to`, so `home` has no default next. */
19
+ function nextScreen(name, ctx, interactive) {
20
+ switch (name) {
21
+ case "signin":
22
+ // Interactive: land on the hub. Non-interactive (CI/pipe): no menu to drive, so run the
23
+ // linear setup straight through, then the terminal home report auto-exits.
24
+ return interactive ? "home" : "connect";
25
+ case "connect":
26
+ // Both paths end at the table-scope editor: a brand-new project is provisioned first, an
27
+ // already-watched one goes straight to adjusting which tables are watched.
28
+ return ctx.alreadyWatching ? "scope" : "agent";
29
+ case "agent":
30
+ return "scope";
31
+ case "scope":
32
+ case "mcp":
33
+ return "home";
34
+ default:
35
+ return null;
36
+ }
37
+ }
38
+ /** Where escape goes from a screen: one level back, or `null` to quit (top level). */
39
+ function backTarget(name) {
40
+ switch (name) {
41
+ case "manageprojects":
42
+ case "mcp":
43
+ return "home";
44
+ case "managetables":
45
+ return "manageprojects";
46
+ case "connect":
47
+ case "agent":
48
+ case "scope":
49
+ // These make up the "onboard a new project" sub-flow launched from the project picker.
50
+ return "manageprojects";
51
+ default:
52
+ return null; // signin / home → quit
53
+ }
54
+ }
55
+ export function App({ services, fast, interactive, signedIn, demo }) {
56
+ const [screen, setScreen] = useState("signin");
57
+ const [ctx, setCtx] = useState({});
58
+ // onDone reads the current screen + ctx to compute the default next screen; refs keep those reads
59
+ // fresh without rebuilding the callback on every transition.
60
+ const screenRef = useRef(screen);
61
+ screenRef.current = screen;
62
+ const ctxRef = useRef(ctx);
63
+ ctxRef.current = ctx;
64
+ // Global escape handling. Runs alongside each screen's own useInput (Ink delivers every key to
65
+ // every active handler). The sign-in screen owns escape itself (it steps back through email/code
66
+ // entry instead of quitting), so we defer to it there. In any other sub-screen escape steps BACK
67
+ // one level toward the hub; at the hub it quits. exit() already restores the terminal synchronously
68
+ // in Ink; the follow-up process.exit guarantees promptness — it doesn't wait on in-flight awaits
69
+ // (OAuth handback polling, the agent log tail) that could otherwise keep the event loop alive.
70
+ // 130 = conventional "terminated by the user" code, so a scripted caller can tell an abort from a
71
+ // completed run. Guarded on `interactive` (useInput needs a raw-mode TTY).
72
+ const { exit } = useApp();
73
+ useInput((_input, key) => {
74
+ if (!key.escape)
75
+ return;
76
+ if (screenRef.current === "signin")
77
+ return; // SignIn owns escape (step back through text entry / quit)
78
+ const back = backTarget(screenRef.current);
79
+ if (back === null) {
80
+ exit();
81
+ process.exit(130);
82
+ }
83
+ else {
84
+ setScreen(back); // step back toward the hub; screens re-derive their state from the server
85
+ }
86
+ }, { isActive: interactive });
21
87
  const onDone = useCallback((patch, opts) => {
22
- setCtx((c) => {
23
- const next = { ...c, ...patch };
24
- setPhase((p) => {
25
- // `to` jumps to a named phase (skipping intermediate steps, e.g. an already-watched project skips
26
- // setup+scope); default is the next step. Never jump backwards.
27
- const target = opts?.to ? PHASES.findIndex((ph) => ph.name === opts.to) : p + 1;
28
- const nextIndex = target > p ? target : p + 1;
29
- const nextPhase = PHASES[nextIndex];
30
- // Persist resume state; clear once the flow reaches the terminal report.
31
- if (!nextPhase || nextPhase.name === "report")
32
- clearProgress();
33
- else
34
- saveProgress({
35
- phase: nextPhase.name,
36
- ...(next.projectRef ? { projectRef: next.projectRef } : {}),
37
- ...(next.connectionId ? { connectionId: next.connectionId } : {}),
38
- ...(next.alreadyWatching ? { alreadyWatching: true } : {}),
39
- });
40
- return nextIndex;
41
- });
42
- return next;
43
- });
44
- }, []);
45
- const current = PHASES[phase];
46
- return (_jsx(WizardProvider, { value: { services, fast, interactive, signedIn, demo }, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(BrandBar, {}), current ? _jsx(current.Comp, { ctx: ctx, onDone: onDone }) : null] }) }));
88
+ // Compute from refs, then fire the two state updates as siblings. (Calling setScreen from
89
+ // inside the setCtx updater makes that updater impure, which React may re-run — here it
90
+ // wedged the event loop so sub-screen timers never fired.)
91
+ const next = { ...ctxRef.current, ...patch };
92
+ const target = opts?.to ?? nextScreen(screenRef.current, next, interactive);
93
+ setCtx(next);
94
+ setScreen(target ?? "home");
95
+ }, [interactive]);
96
+ const Current = SCREENS[screen];
97
+ return (_jsx(WizardProvider, { value: { services, fast, interactive, signedIn, demo }, children: _jsxs(Box, { flexDirection: "column", children: [_jsx(BrandBar, {}), Current ? _jsx(Current, { ctx: ctx, onDone: onDone }) : null] }) }));
47
98
  }
package/dist/cli.js CHANGED
@@ -1,10 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { render } from "ink";
4
+ import { rmSync } from "node:fs";
5
+ import { createRequire } from "node:module";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
4
8
  import { SodabaseClient } from "./api/client.js";
5
9
  import { FakeClient } from "./api/fakeClient.js";
6
10
  import { App } from "./app.js";
7
- import { clearProgress, loadProgress } from "./config/flowState.js";
8
11
  import { clearCreds, loadCreds } from "./config/tokenStore.js";
9
12
  const argv = process.argv.slice(2);
10
13
  const args = new Set(argv);
@@ -31,20 +34,31 @@ if (args.has("--help") || args.has("-h")) {
31
34
  process.exit(0);
32
35
  }
33
36
  if (args.has("--version")) {
34
- process.stdout.write("sodabase 0.0.0-dev\n");
37
+ // Read the real version from package.json (one level up from dist/cli.js, and included in the tarball) so it
38
+ // never goes stale — the old hardcoded string shipped as 0.0.0-dev against a 0.1.0 package.
39
+ const { version } = createRequire(import.meta.url)("../package.json");
40
+ process.stdout.write(`sodabase ${version}\n`);
35
41
  process.exit(0);
36
42
  }
37
- // Sign out: drop the saved session (and resume state) and stop.
43
+ // Sign out: drop the saved session and stop.
38
44
  if (args.has("--logout")) {
39
45
  clearCreds();
40
- clearProgress();
46
+ // Best-effort: remove the legacy resume file an older build may have left behind. It's not a secret
47
+ // (tokens live in credentials.json, cleared above), but a clean sign-out shouldn't leave a file
48
+ // naming your last project on disk. Nothing writes it anymore, so this only ever cleans up.
49
+ try {
50
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
51
+ rmSync(join(base, "sodabase", "progress.json"));
52
+ }
53
+ catch {
54
+ /* already gone */
55
+ }
41
56
  process.stdout.write("Signed out of Sodabase.\n");
42
57
  process.exit(0);
43
58
  }
44
59
  // Force a fresh sign-in: clear the saved session first, then run normally so it re-prompts.
45
60
  if (args.has("--login")) {
46
61
  clearCreds();
47
- clearProgress();
48
62
  }
49
63
  const demo = args.has("--demo");
50
64
  const fast = args.has("--fast") || demo;
@@ -53,8 +67,6 @@ const fast = args.has("--fast") || demo;
53
67
  // piped/CI run (no TTY) auto-advances. Opt out explicitly with --no-input.
54
68
  const interactive = !!process.stdin.isTTY && !args.has("--no-input");
55
69
  let signedIn = false;
56
- let startPhase;
57
- let initialCtx;
58
70
  const services = demo
59
71
  ? new FakeClient({ fast })
60
72
  : (() => {
@@ -66,22 +78,6 @@ const services = demo
66
78
  c.setBearer(creds.accessToken);
67
79
  signedIn = !creds.expiresAt || creds.expiresAt > Date.now() + 60_000;
68
80
  }
69
- // Resume only when authenticated — re-attaching to the server-side state needs the token.
70
- if (signedIn) {
71
- const prog = loadProgress();
72
- if (prog) {
73
- startPhase = prog.phase;
74
- const ctx = {};
75
- if (prog.projectRef)
76
- ctx.projectRef = prog.projectRef;
77
- if (prog.connectionId)
78
- ctx.connectionId = prog.connectionId;
79
- if (prog.alreadyWatching)
80
- ctx.alreadyWatching = true;
81
- if (Object.keys(ctx).length)
82
- initialCtx = ctx;
83
- }
84
- }
85
81
  return c;
86
82
  })();
87
- render(_jsx(App, { services: services, fast: fast, interactive: interactive, signedIn: signedIn, demo: demo, ...(startPhase ? { startPhase } : {}), ...(initialCtx ? { initialCtx } : {}) }));
83
+ render(_jsx(App, { services: services, fast: fast, interactive: interactive, signedIn: signedIn, demo: demo }));
package/dist/ui.js CHANGED
@@ -31,30 +31,16 @@ export function BrandBar() {
31
31
  function Eyebrow({ children }) {
32
32
  return (_jsxs(Text, { color: "green", bold: true, children: ["\u25E7 ", children] }));
33
33
  }
34
- const sevColor = { bad: "red", warn: "yellow", ok: "green" };
35
- // ── Phase: boot + detect ─────────────────────────────────────────────────────────
36
- export function BootDetect({ onDone }) {
37
- const { services, fast } = useWizard();
38
- const spin = useSpinner();
39
- const [project, setProject] = useState(null);
40
- useEffect(() => {
41
- let on = true;
42
- (async () => {
43
- const p = await services.detectProject();
44
- if (!on)
45
- return;
46
- setProject(p);
47
- await sleep(fast ? 120 : 900);
48
- if (on)
49
- onDone({ project: p });
50
- })();
51
- return () => {
52
- on = false;
53
- };
54
- }, []);
55
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: project ? "Project detected" : "Sodabase starting up" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { children: "We'll set up data-quality monitoring for your Supabase project." }), _jsx(Text, { dimColor: true, children: "Read-only, always. The only write is one scoped, audited read-only role." })] }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: !project ? (_jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Detecting Supabase project\u2026"] })) : (_jsxs(_Fragment, { children: [_jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Directory ", _jsx(Text, { dimColor: true, children: project.directory })] }), _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Framework ", project.framework] }), _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Database ", _jsx(Text, { dimColor: true, children: project.database })] })] })) })] }));
34
+ // ── Phase: detect + GoTrue sign-in (one screen) ──────────────────────────────────
35
+ /** The detection facts block, with labels aligned in a left column (Directory / Framework / …). */
36
+ function ProjectFacts({ project }) {
37
+ const pad = (s) => s.padEnd(10);
38
+ // Empty framework/projectRef = detection missed; name the real reason so we never claim a present
39
+ // file is absent (the file may exist but lack the Supabase dep / project_id).
40
+ const frameworkMiss = project.hasPackageJson ? "no Supabase dependency in package.json" : "package.json not found";
41
+ const refMiss = project.hasConfigToml ? "no project_id in supabase/config.toml" : "supabase/config.toml not found";
42
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { dimColor: true, children: pad("Directory") }), _jsx(Text, { color: "green", children: "\u2714 " }), project.directory] }), _jsxs(Text, { children: [_jsx(Text, { dimColor: true, children: pad("Framework") }), project.framework ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: "green", children: "\u2714 " }), project.framework] })) : (_jsxs(Text, { dimColor: true, children: ["\u2013 ", frameworkMiss] }))] }), _jsxs(Text, { children: [_jsx(Text, { dimColor: true, children: pad("Supabase") }), project.projectRef ? (_jsxs(_Fragment, { children: [_jsx(Text, { color: "green", children: "\u2714 " }), "project ref ", _jsx(Text, { dimColor: true, children: project.projectRef })] })) : (_jsxs(Text, { dimColor: true, children: ["\u2013 ", refMiss] }))] })] }));
56
43
  }
57
- // ── Phase: GoTrue sign-in ────────────────────────────────────────────────────────
58
44
  const PROVIDERS = [
59
45
  { id: "github", label: "GitHub" },
60
46
  { id: "google", label: "Google" },
@@ -79,6 +65,7 @@ function friendlySignInError(raw) {
79
65
  }
80
66
  export function SignIn({ onDone }) {
81
67
  const { services, signedIn, demo, interactive } = useWizard();
68
+ const { exit } = useApp();
82
69
  const spin = useSpinner();
83
70
  const [stage, setStage] = useState(interactive ? "pick" : "signing");
84
71
  const [cursor, setCursor] = useState(0);
@@ -86,6 +73,7 @@ export function SignIn({ onDone }) {
86
73
  const [email, setEmail] = useState("");
87
74
  const [code, setCode] = useState("");
88
75
  const [err, setErr] = useState(null);
76
+ const [project, setProject] = useState(null);
89
77
  const mounted = useRef(true);
90
78
  useEffect(() => () => void (mounted.current = false), []);
91
79
  // Finish sign-in the same way for every path: set the bearer, persist (never in --demo), advance.
@@ -151,13 +139,50 @@ export function SignIn({ onDone }) {
151
139
  }
152
140
  useEffect(() => {
153
141
  if (signedIn) {
154
- onDone({}); // a valid session is already loaded — skip sign-in
142
+ onDone({}); // a valid session is already loaded — skip detect + sign-in
155
143
  return;
156
144
  }
145
+ // Detect the project in the background; the sign-in picker is usable while the facts fill in.
146
+ let on = true;
147
+ void (async () => {
148
+ try {
149
+ const p = await services.detectProject();
150
+ if (on)
151
+ setProject(p);
152
+ }
153
+ catch {
154
+ /* detection is best-effort — the picker still works without the facts */
155
+ }
156
+ })();
157
157
  if (!interactive)
158
158
  void go(); // non-interactive: env/default provider, no picker
159
+ return () => void (on = false);
159
160
  }, []);
160
161
  useInput((input, key) => {
162
+ // Escape steps back through the text-entry stages (so it never destroys a half-typed sign-in);
163
+ // from the picker or a transient stage it quits. SignIn owns escape entirely — App's global
164
+ // handler defers to the sign-in screen.
165
+ if (key.escape) {
166
+ if (stage === "email") {
167
+ setErr(null);
168
+ setStage("pick");
169
+ }
170
+ else if (stage === "code") {
171
+ setErr(null);
172
+ setCode("");
173
+ setStage("email");
174
+ }
175
+ else if (stage === "error") {
176
+ setErr(null);
177
+ setCode("");
178
+ setStage("pick");
179
+ }
180
+ else {
181
+ exit();
182
+ process.exit(130); // user abort
183
+ }
184
+ return;
185
+ }
161
186
  if (stage === "pick") {
162
187
  if (key.upArrow)
163
188
  setCursor((c) => Math.max(0, c - 1));
@@ -204,12 +229,15 @@ export function SignIn({ onDone }) {
204
229
  setStage("pick");
205
230
  }
206
231
  }
207
- }, { isActive: interactive && (stage === "pick" || stage === "email" || stage === "code" || stage === "error") });
232
+ },
233
+ // Active in every stage so escape is handled even during the transient sending/verifying/signing
234
+ // states (where it quits); the per-stage branches above guard the non-escape keys.
235
+ { isActive: interactive });
208
236
  const providerLabel = PROVIDERS.find((p) => p.id === chosen)?.label ?? chosen ?? "your provider";
209
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Sign in to Sodabase" }), signedIn ? (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Already signed in ", _jsx(Text, { dimColor: true, children: "(using your saved session)" })] }) })) : stage === "pick" ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "How do you want to sign in?" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: PROVIDERS.map((p, i) => {
210
- const here = i === cursor;
211
- return (_jsxs(Text, { color: here ? "green" : undefined, children: [here ? "❯ " : " ", p.label] }, p.id));
212
- }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 enter to continue \u00B7 GitHub/Google open your browser" }) })] })) : stage === "email" ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Enter your email \u2014 we'll send you a sign-in code." }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: ["Email: ", _jsx(Text, { color: "green", children: email }), _jsx(Text, { inverse: true, children: " " })] }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "type to edit \u00B7 backspace to delete \u00B7 enter to send \u00B7 Ctrl-C to quit" }) })] })) : stage === "sending" ? (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Sending a sign-in code to ", email, "\u2026"] }) })) : stage === "code" ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["We emailed a sign-in code to ", email, ". Enter it below."] }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: ["Code: ", _jsx(Text, { color: "green", children: code }), _jsx(Text, { inverse: true, children: " " })] }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to verify \u00B7 backspace to delete \u00B7 press r after a failure to start over" }) })] })) : stage === "verifying" ? (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Verifying your code\u2026"] }) })) : stage === "error" && err ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { color: "red", children: err.text }), err.hint && _jsx(Text, { dimColor: true, children: err.hint }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "press r to start over \u00B7 Ctrl-C to quit" }) }))] })) : (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Opening your browser to sign in with ", providerLabel, "\u2026"] }) }))] }));
237
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: signedIn ? "Signed in" : "Project detected" }), signedIn ? (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Already signed in ", _jsx(Text, { dimColor: true, children: "(using your saved session)" })] }) })) : (_jsxs(_Fragment, { children: [_jsx(Box, { marginTop: 1, flexDirection: "column", children: _jsx(Text, { children: "We'll set up data-quality monitoring for your Supabase project \u2014 watching freshness, volume and quality drift, without touching a line of your code." }) }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: !project ? (_jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Detecting Supabase project\u2026"] })) : (_jsx(ProjectFacts, { project: project })) }), stage === "pick" ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "How do you want to sign in?" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: PROVIDERS.map((p, i) => {
238
+ const here = i === cursor;
239
+ return (_jsxs(Text, { color: here ? "green" : undefined, children: [here ? "❯ " : " ", p.label] }, p.id));
240
+ }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 enter to continue \u00B7 GitHub/Google open your browser \u00B7 esc to quit" }) })] })) : stage === "email" ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Enter your email \u2014 we'll send you a sign-in code." }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: ["Email: ", _jsx(Text, { color: "green", children: email }), _jsx(Text, { inverse: true, children: " " })] }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "type to edit \u00B7 backspace to delete \u00B7 enter to send \u00B7 esc to go back" }) })] })) : stage === "sending" ? (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Sending a sign-in code to ", email, "\u2026"] }) })) : stage === "code" ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["We emailed a sign-in code to ", email, ". Enter it below."] }), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: ["Code: ", _jsx(Text, { color: "green", children: code }), _jsx(Text, { inverse: true, children: " " })] }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to verify \u00B7 backspace to delete \u00B7 esc to go back" }) })] })) : stage === "verifying" ? (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Verifying your code\u2026"] }) })) : stage === "error" && err ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { color: "red", children: err.text }), err.hint && _jsx(Text, { dimColor: true, children: err.hint }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "press r to start over \u00B7 esc to go back" }) }))] })) : (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Opening your browser to sign in with ", providerLabel, "\u2026"] }) }))] }))] }));
213
241
  }
214
242
  // ── Phase: connect (multi-step: authorize → list → pick project) ─────────────────
215
243
  /** Short status tags shown next to a project in the picker: "watching" (already set up in this workspace) and
@@ -230,16 +258,6 @@ function isWatchable(p) {
230
258
  return !p.status || p.status === "ACTIVE_HEALTHY";
231
259
  }
232
260
  const issuesLabel = (n) => `${n} ${n === 1 ? "issue" : "issues"}`;
233
- /** Aligned list of the workspace's watched projects with their live issue counts. The count is the SUM of
234
- * monitor signals + data-quality findings (the API exposes them separately; the CLI shows one number). Green =
235
- * all clear, yellow = has issues. Names are padded to a common width so the issue column lines up. */
236
- function WatchedProjects({ projects }) {
237
- const width = projects.reduce((w, p) => Math.max(w, p.name.length), 0);
238
- return (_jsx(Box, { flexDirection: "column", children: projects.map((p) => {
239
- const n = totalIssues(p);
240
- return (_jsxs(Text, { children: [" ", p.name.padEnd(width), " ", _jsx(Text, { color: n > 0 ? "yellow" : "green", children: issuesLabel(n) })] }, p.ref));
241
- }) }));
242
- }
243
261
  export function Connect({ onDone }) {
244
262
  const { services, interactive } = useWizard();
245
263
  const spin = useSpinner();
@@ -251,11 +269,15 @@ export function Connect({ onDone }) {
251
269
  const [error, setError] = useState(null);
252
270
  useEffect(() => {
253
271
  let on = true;
272
+ // Abort the authorize poll when we leave this screen (escape back to the hub) so an abandoned
273
+ // connect doesn't keep polling for up to 5 minutes — and a re-entry can't start a second,
274
+ // competing poll loop against the same handback.
275
+ const controller = new AbortController();
254
276
  (async () => {
255
277
  try {
256
- // connect() opens the browser, captures code+state at our loopback, and self-completes
257
- // the callback with our own Bearer — no browser web session needed (fixes the 401/403).
258
- const { connectionId: cid, alreadyConnected: ac } = await services.connect();
278
+ // connect() opens the browser, polls the hosted handback, and self-completes with our own
279
+ // Bearer — no browser web session needed (fixes the 401/403).
280
+ const { connectionId: cid, alreadyConnected: ac } = await services.connect(controller.signal);
259
281
  if (!on)
260
282
  return;
261
283
  setConnectionId(cid);
@@ -274,12 +296,13 @@ export function Connect({ onDone }) {
274
296
  finish(cid, projs[0]);
275
297
  }
276
298
  catch (e) {
277
- if (on)
299
+ if (on && !controller.signal.aborted)
278
300
  setError(e instanceof Error ? e.message : String(e));
279
301
  }
280
302
  })();
281
303
  return () => {
282
304
  on = false;
305
+ controller.abort();
283
306
  };
284
307
  }, []);
285
308
  function finish(connId, project) {
@@ -292,14 +315,10 @@ export function Connect({ onDone }) {
292
315
  }
293
316
  const ref = project?.ref ?? "";
294
317
  setChosen(ref);
295
- if (project?.watching) {
296
- // Already monitored — there's nothing new to provision or adjust, so skip setup + the (empty) scope
297
- // screen and go straight to the status view.
298
- onDone({ connectionId: connId, projectRef: ref, alreadyWatching: true }, { to: "findings" });
299
- }
300
- else {
301
- onDone({ connectionId: connId, projectRef: ref });
302
- }
318
+ // alreadyWatching routes the hub: an already-watched project skips provisioning and goes straight to
319
+ // adjusting its tables; a new one is provisioned first. Set it explicitly (not just when true) so a
320
+ // later pick of a NEW project resets the flag left over from a previous "manage" round.
321
+ onDone({ connectionId: connId, projectRef: ref, alreadyWatching: !!project?.watching });
303
322
  }
304
323
  useInput((_i, key) => {
305
324
  if (!projects || chosen)
@@ -312,7 +331,7 @@ export function Connect({ onDone }) {
312
331
  finish(connectionId, projects[cursor]);
313
332
  }, { isActive: interactive && !!projects && !chosen });
314
333
  const picking = interactive && projects && projects.length > 1 && !chosen;
315
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Authorize your database" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: error ? (_jsx(Text, { color: "red", children: error })) : !connectionId ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Opening your browser to authorize\u2026"] }), _jsx(Text, { dimColor: true, children: "Read-only \u2014 no connection string to paste. Approve on Supabase, then return here." })] })) : !projects ? (_jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Loading your projects\u2026"] })) : picking ? (_jsxs(_Fragment, { children: [_jsx(Text, { children: "Pick the project to watch:" }), projects.map((p, i) => (_jsxs(Text, { color: i === cursor ? "green" : undefined, children: [i === cursor ? "❯ " : " ", p.name, " ", _jsxs(Text, { dimColor: true, children: ["(", p.ref, ")"] }), projectTags(p).map((t) => (_jsxs(Text, { color: t.color, children: [" ", "\u00B7 ", t.label] }, t.label)))] }, p.ref))), _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 enter select \u00B7 green = watching \u00B7 yellow = offline" })] })) : (_jsxs(_Fragment, { children: [alreadyConnected && (_jsxs(Text, { dimColor: true, children: [_jsx(Text, { color: "green", children: "\u2713" }), " Already connected \u2014 continuing on your existing connection."] })), _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Connected \u00B7 project ", _jsx(Text, { bold: true, children: chosen ?? projects[0]?.ref ?? "—" }), _jsx(Text, { color: "green", children: " 🔒 read-only, audited" })] })] })) })] }));
334
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Authorize your database" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: error ? (_jsx(Text, { color: "red", children: error })) : !connectionId ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Opening your browser to authorize\u2026"] }), _jsx(Text, { dimColor: true, children: "Read-only \u2014 no connection string to paste. Approve on Supabase, then return here." })] })) : !projects ? (_jsxs(Text, { children: [_jsx(Text, { color: "green", children: spin }), " Loading your projects\u2026"] })) : picking ? (_jsxs(_Fragment, { children: [_jsx(Text, { children: "Pick the project to watch:" }), projects.map((p, i) => (_jsxs(Text, { color: i === cursor ? "green" : undefined, children: [i === cursor ? "❯ " : " ", p.name, " ", _jsxs(Text, { dimColor: true, children: ["(", p.ref, ")"] }), projectTags(p).map((t) => (_jsxs(Text, { color: t.color, children: [" ", "\u00B7 ", t.label] }, t.label)))] }, p.ref))), _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 enter select \u00B7 green = watching \u00B7 yellow = offline \u00B7 esc to go back" })] })) : (_jsxs(_Fragment, { children: [alreadyConnected && (_jsxs(Text, { dimColor: true, children: [_jsx(Text, { color: "green", children: "\u2713" }), " Already connected \u2014 continuing on your existing connection."] })), _jsxs(Text, { children: [_jsx(Text, { color: "green", children: "\u2714" }), " Connected \u00B7 project ", _jsx(Text, { bold: true, children: chosen ?? projects[0]?.ref ?? "—" }), _jsx(Text, { color: "green", children: " 🔒 read-only, audited" })] })] })) })] }));
316
335
  }
317
336
  // ── Phase: the server-side onboarding job (two-panel) ─────────────────────────────
318
337
  // Human labels for the backend onboarding job's step names (machine keys). Unknown names fall back to the raw
@@ -449,65 +468,28 @@ export function ScopeAdjust({ onDone }) {
449
468
  const on = sel[i];
450
469
  const here = interactive && i === cursor;
451
470
  return (_jsxs(Text, { color: on ? "green" : undefined, dimColor: !on, children: [here ? "❯ " : " ", on ? "[x]" : "[ ]", " ", p.dataset, " ", _jsxs(Text, { dimColor: true, children: ["\u00B7 ", p.type] })] }, p.id));
452
- })) }), _jsx(Box, { marginTop: 1, children: interactive && !committed && proposals && proposals.length > 0 ? (_jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 space toggle \u00B7 enter confirm" })) : (_jsx(Text, { dimColor: true, children: committed ? "saved" : "accepting recommended…" })) })] }));
453
- }
454
- // ── Phase: day-1 scan — status + dashboard link (no REST source) ──────────────────
455
- export function Findings({ ctx, onDone }) {
456
- const { services, fast, interactive } = useWizard();
457
- const [findings, setFindings] = useState(null);
458
- const [projects, setProjects] = useState(null);
459
- const [ready, setReady] = useState(false);
460
- useEffect(() => {
461
- let on = true;
462
- (async () => {
463
- if (ctx.alreadyWatching) {
464
- // Already monitored → show the workspace's watched projects + live issue counts, not the scan pitch.
465
- try {
466
- const p = await services.dashboardProjects();
467
- if (on)
468
- setProjects(p);
469
- }
470
- catch {
471
- if (on)
472
- setProjects([]); // fall back to the plain message if the status read fails
473
- }
474
- }
475
- else if (services.illustrativeFindings) {
476
- const f = await services.illustrativeFindings();
477
- if (on)
478
- setFindings(f);
479
- }
480
- if (!on)
481
- return;
482
- setReady(true);
483
- if (!interactive) {
484
- await sleep(fast ? 400 : 1600);
485
- if (on)
486
- onDone({});
487
- }
488
- })();
489
- return () => {
490
- on = false;
491
- };
492
- }, []);
493
- useInput((_i, key) => {
494
- if (key.return)
495
- onDone({});
496
- }, { isActive: interactive && ready });
497
- if (ctx.alreadyWatching) {
498
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Already monitored" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [projects === null ? (_jsx(Text, { dimColor: true, children: "loading your projects\u2026" })) : projects.length > 0 ? (_jsxs(_Fragment, { children: [_jsx(Text, { dimColor: true, children: "You're already watching these \u2014 setup skipped:" }), _jsx(Box, { marginTop: 1, children: _jsx(WatchedProjects, { projects: projects }) })] })) : (_jsx(Text, { dimColor: true, children: "You're already monitoring this project \u2014 setup skipped." })), _jsxs(Box, { marginTop: 1, children: [_jsx(Text, { dimColor: true, children: "Dashboard \u2192 " }), _jsxs(Text, { color: "cyan", children: ["https://sodabase.io/projects/", ctx.projectRef ?? "…"] })] }), interactive && ready && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })] }));
499
- }
500
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Day-1 quality scan" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { children: "The scan runs in the background (async) \u2014 results land in your dashboard:" }), _jsxs(Text, { children: [" ", _jsxs(Text, { color: "cyan", children: ["https://sodabase.io/projects/", ctx.projectRef ?? "…", "/data-trust"] })] })] }), findings && (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Illustrative \u2014 what you'd typically see first:" }), findings.map((f) => (_jsxs(Text, { children: [" ", _jsx(Text, { color: sevColor[f.severity], children: "\u25CF" }), " ", f.column, " ", _jsxs(Text, { dimColor: true, children: ["(", f.family, ") \u2014 ", f.detail] })] }, f.column)))] })), interactive && ready && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] }));
471
+ })) }), _jsx(Box, { marginTop: 1, children: interactive && !committed && proposals && proposals.length > 0 ? (_jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 space toggle \u00B7 enter confirm \u00B7 esc to go back" })) : (_jsx(Text, { dimColor: true, children: committed ? "saved" : "accepting recommended…" })) })] }));
501
472
  }
502
473
  // ── Phase: consented in-flow MCP install ─────────────────────────────────────────
474
+ // These ids are forwarded verbatim to BOTH `add-mcp -a` and `skills -a` (see client.ts).
475
+ // Keep every id in this list valid for both CLIs — all three are today; an id only one of
476
+ // them knows would make that tool's install fail (non-fatal, but all-or-nothing for skills).
503
477
  const AGENTS = ["claude-code", "cursor", "codex"];
504
478
  export function McpInstall({ onDone }) {
505
479
  const { services, fast, interactive } = useWizard();
506
480
  const [sel, setSel] = useState([true, false, false]);
507
481
  const [cursor, setCursor] = useState(0);
508
482
  const [result, setResult] = useState(null);
483
+ const [skillResult, setSkillResult] = useState(null);
484
+ const [skillError, setSkillError] = useState(null);
485
+ // The agents the MCP install actually wrote, so the skill-error hold can advance with the right context.
486
+ const [installedAgents, setInstalledAgents] = useState([]);
509
487
  const [busy, setBusy] = useState(false);
510
488
  const [error, setError] = useState(null);
489
+ // MCP install is reached only from the hub menu (interactive). Back-navigation can unmount this
490
+ // mid-install, so guard every post-await state update.
491
+ const mounted = useRef(true);
492
+ useEffect(() => () => void (mounted.current = false), []);
511
493
  async function run(choices) {
512
494
  if (choices.length === 0) {
513
495
  onDone({ installed: [] });
@@ -516,36 +498,51 @@ export function McpInstall({ onDone }) {
516
498
  setBusy(true);
517
499
  try {
518
500
  const r = await services.installMcp(choices);
501
+ if (!mounted.current)
502
+ return;
519
503
  setResult(r);
504
+ setInstalledAgents(choices);
505
+ // Also install the trust-advisor skill to the same agents. Non-fatal: the MCP (the main
506
+ // thing) is already in place, so a skill failure shouldn't block onboarding — we surface it
507
+ // with a manual fallback instead.
508
+ let skillFailed = false;
509
+ try {
510
+ const s = await services.installSkill(choices);
511
+ if (mounted.current)
512
+ setSkillResult(s);
513
+ }
514
+ catch (e) {
515
+ if (mounted.current)
516
+ setSkillError(e instanceof Error ? e.message : String(e));
517
+ skillFailed = true;
518
+ }
520
519
  await sleep(fast ? 300 : 900);
521
- onDone({ installed: choices });
520
+ if (!mounted.current)
521
+ return;
522
+ // Hold on a skill failure so the manual fallback is readable/actionable (enter advances);
523
+ // otherwise finish.
524
+ if (skillFailed)
525
+ setBusy(false);
526
+ else
527
+ onDone({ installed: choices });
522
528
  }
523
529
  catch (e) {
524
530
  // Don't silently swallow it — the user should know the MCP didn't install, and how to add it by hand.
531
+ if (!mounted.current)
532
+ return;
525
533
  setBusy(false);
526
534
  setError(e instanceof Error ? e.message : String(e));
527
- if (!interactive) {
528
- await sleep(fast ? 300 : 1200);
529
- onDone({ installed: [] });
530
- }
531
535
  }
532
536
  }
533
- useEffect(() => {
534
- if (interactive)
535
- return;
536
- let on = true;
537
- (async () => {
538
- await sleep(fast ? 300 : 1000);
539
- if (on)
540
- await run(["claude-code"]);
541
- })();
542
- return () => {
543
- on = false;
544
- };
545
- }, []);
546
537
  useInput((input, key) => {
547
538
  if (busy)
548
539
  return;
540
+ if (skillError) {
541
+ // Holding after a non-fatal skill failure: the MCP already landed, so advance on enter.
542
+ if (key.return)
543
+ onDone({ installed: installedAgents });
544
+ return;
545
+ }
549
546
  if (error) {
550
547
  if (key.return)
551
548
  onDone({ installed: [] });
@@ -561,18 +558,167 @@ export function McpInstall({ onDone }) {
561
558
  void run([]);
562
559
  else if (key.return)
563
560
  void run(AGENTS.filter((_, i) => sel[i]));
564
- }, { isActive: interactive && !busy && !result });
565
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Set up your coding agent (optional)" }), error ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { color: "yellow", children: ["Couldn't auto-install the MCP: ", error] }), _jsx(Text, { dimColor: true, children: "Add it yourself (Claude Code):" }), _jsxs(Text, { color: "cyan", children: [" ", "claude mcp add --transport http sodabase https://sodabase.io/mcp"] }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })) : result ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["Ran: ", result.command] }), result.wrote.map((w) => (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " ", w.agent, " ", _jsxs(Text, { dimColor: true, children: ["\u2192 ", w.path] })] }, w.agent))), _jsx(Text, { color: "green", children: "Ready next time you restart your agent." })] })) : (_jsxs(_Fragment, { children: [_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Install the Sodabase MCP so your agent can ask \"is this data safe to trust?\"" }), _jsx(Text, { dimColor: true, children: "Explicit \u2014 we show the exact change and only write on your confirm." })] }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: AGENTS.map((a, i) => {
561
+ }, { isActive: interactive && !busy && (!result || skillError !== null) });
562
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Set up your coding agent (optional)" }), error ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { color: "yellow", children: ["Couldn't auto-install the MCP: ", error] }), _jsx(Text, { dimColor: true, children: "Add it yourself (Claude Code):" }), _jsxs(Text, { color: "cyan", children: [" ", "claude mcp add --transport http sodabase https://sodabase.io/mcp"] }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })) : result ? (_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { dimColor: true, children: ["Ran: ", result.command] }), result.wrote.map((w) => (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " ", w.agent, " ", _jsxs(Text, { dimColor: true, children: ["\u2192 ", w.path] })] }, w.agent))), skillResult && (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " trust-advisor skill ", _jsx(Text, { dimColor: true, children: "\u2192 sodabase/agent-skills" })] })), skillError && (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "yellow", children: ["Couldn't install the trust-advisor skill: ", skillError] }), _jsx(Text, { dimColor: true, children: "Add it yourself:" }), _jsxs(Text, { color: "cyan", children: [" ", "npx skills add sodabase/agent-skills"] })] })), _jsx(Text, { color: "green", children: "Ready next time you restart your agent." }), skillError && interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to continue" }) }))] })) : (_jsxs(_Fragment, { children: [_jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Install the Sodabase MCP + trust-advisor skill so your agent can ask \"is this data safe to trust?\"" }), _jsx(Text, { dimColor: true, children: "Explicit \u2014 we show the exact change and only write on your confirm." })] }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: AGENTS.map((a, i) => {
566
563
  const on = sel[i];
567
564
  const here = interactive && i === cursor;
568
565
  return (_jsxs(Text, { color: on ? "green" : undefined, dimColor: !on, children: [here ? "❯ " : " ", on ? "[x]" : "[ ]", " ", a] }, a));
569
- }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: interactive ? "↑↓ move · space toggle · enter install · n skip" : "installing for claude-code…" }) })] }))] }));
566
+ }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: interactive ? "↑↓ move · space toggle · enter install · n skip · esc to go back" : "installing for claude-code…" }) })] }))] }));
567
+ }
568
+ // ── Phase: manage projects (the hub's "Manage projects" entry) ───────────────────
569
+ // A picker over the projects already being watched; selecting one drills into its watched tables.
570
+ // A final row onboards a brand-new project (the Supabase authorize + pick flow).
571
+ export function ManageProjects({ onDone }) {
572
+ const { services, interactive } = useWizard();
573
+ const [projects, setProjects] = useState(null);
574
+ const [cursor, setCursor] = useState(0);
575
+ const [error, setError] = useState(null);
576
+ useEffect(() => {
577
+ let on = true;
578
+ (async () => {
579
+ try {
580
+ const p = await services.dashboardProjects();
581
+ if (on)
582
+ setProjects(p);
583
+ }
584
+ catch (e) {
585
+ if (on)
586
+ setError(e instanceof Error ? e.message : String(e));
587
+ }
588
+ })();
589
+ return () => {
590
+ on = false;
591
+ };
592
+ }, []);
593
+ const onboardRow = projects?.length ?? 0; // the "+ onboard a new project" row sits after the projects
594
+ useInput((_i, key) => {
595
+ if (!projects)
596
+ return;
597
+ if (key.upArrow)
598
+ setCursor((c) => Math.max(0, c - 1));
599
+ else if (key.downArrow)
600
+ setCursor((c) => Math.min(onboardRow, c + 1));
601
+ else if (key.return) {
602
+ const p = projects[cursor];
603
+ if (cursor < projects.length && p)
604
+ onDone({ projectRef: p.ref }, { to: "managetables" });
605
+ else
606
+ onDone({}, { to: "connect" }); // onboard a new project
607
+ }
608
+ }, { isActive: interactive && !!projects });
609
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Manage projects" }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "Pick a project to manage its tables, or onboard a new one." }) }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: error ? (_jsx(Text, { color: "red", children: error })) : !projects ? (_jsx(Text, { dimColor: true, children: "loading your projects\u2026" })) : (_jsxs(_Fragment, { children: [projects.map((p, i) => {
610
+ const here = i === cursor;
611
+ const n = totalIssues(p);
612
+ return (_jsxs(Text, { color: here ? "green" : undefined, children: [here ? "❯ " : " ", p.name, " ", _jsxs(Text, { color: n > 0 ? "yellow" : "green", children: ["\u00B7 ", issuesLabel(n)] })] }, p.ref));
613
+ }), _jsxs(Text, { color: cursor === onboardRow ? "green" : undefined, children: [cursor === onboardRow ? "❯ " : " ", "+ Onboard a new project"] })] })) }), projects && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 enter select \u00B7 esc to go back" }) }))] }));
614
+ }
615
+ // ── Phase: manage a project's table monitoring ───────────────────────────────────
616
+ // Lists the selected project's tables with their current watch state (one row per table, watched or
617
+ // not), each toggleable. Toggles commit immediately via the per-table watch endpoint (toggleDataset).
618
+ export function ManageTables({ ctx }) {
619
+ const { services, interactive } = useWizard();
620
+ const projectRef = ctx.projectRef ?? "";
621
+ const [tables, setTables] = useState(null);
622
+ const [cursor, setCursor] = useState(0);
623
+ const [error, setError] = useState(null);
624
+ const mounted = useRef(true);
625
+ useEffect(() => () => void (mounted.current = false), []);
626
+ // Latest tables[] for toggle() to read without a stale closure; the in-flight set serializes
627
+ // writes per row so a rapid double-press can't race or double-fire.
628
+ const tablesRef = useRef(tables);
629
+ tablesRef.current = tables;
630
+ const inFlight = useRef(new Set());
631
+ useEffect(() => {
632
+ if (!projectRef) {
633
+ // Only reachable via ManageProjects, which always passes a ref — guard anyway so we never hit
634
+ // a malformed /projects//datasets URL.
635
+ setError("No project selected.");
636
+ return;
637
+ }
638
+ let on = true;
639
+ (async () => {
640
+ try {
641
+ const rows = await services.projectDatasets(projectRef);
642
+ if (on)
643
+ setTables(rows);
644
+ }
645
+ catch (e) {
646
+ if (on)
647
+ setError(e instanceof Error ? e.message : String(e));
648
+ }
649
+ })();
650
+ return () => {
651
+ on = false;
652
+ };
653
+ }, [projectRef]);
654
+ // Optimistic toggle + immediate save against the real per-table watch endpoint; revert the row if
655
+ // the call fails or the server reports the read grant expired (needsReauth).
656
+ function toggle(i) {
657
+ const t = tablesRef.current?.[i];
658
+ if (!t || inFlight.current.has(t.id))
659
+ return; // one in-flight write per row
660
+ const next = !t.monitored;
661
+ const apply = (monitored) => setTables((rows) => rows?.map((row, j) => (j === i ? { ...row, monitored } : row)) ?? rows);
662
+ apply(next);
663
+ setError(null);
664
+ inFlight.current.add(t.id);
665
+ void (async () => {
666
+ try {
667
+ const r = await services.toggleDataset(projectRef, t.id, next);
668
+ if (!mounted.current)
669
+ return;
670
+ if (next && r.needsReauth) {
671
+ // Only an ENABLE needs the read grant; a dead grant means this watch didn't take effect.
672
+ apply(false);
673
+ setError("Monitoring can't resume — your read-only access expired. Reconnect the project, then retry.");
674
+ }
675
+ else {
676
+ apply(r.monitored); // reconcile with server truth
677
+ }
678
+ }
679
+ catch (e) {
680
+ if (!mounted.current)
681
+ return;
682
+ apply(!next);
683
+ setError(e instanceof Error ? e.message : String(e));
684
+ }
685
+ finally {
686
+ inFlight.current.delete(t.id);
687
+ }
688
+ })();
689
+ }
690
+ useInput((input, key) => {
691
+ if (!tables || tables.length === 0)
692
+ return;
693
+ if (key.upArrow)
694
+ setCursor((c) => Math.max(0, c - 1));
695
+ else if (key.downArrow)
696
+ setCursor((c) => Math.min(tables.length - 1, c + 1));
697
+ else if (input === " " || key.return)
698
+ toggle(cursor);
699
+ }, { isActive: interactive && !!tables });
700
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: "Table monitoring" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { dimColor: true, children: "Toggle a table to watch or unwatch it \u2014 changes save as you go." }), projectRef && (_jsxs(Text, { dimColor: true, children: ["Project ", _jsx(Text, { color: "green", children: projectRef })] }))] }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [error && _jsx(Text, { color: "red", children: error }), !tables ? (_jsx(Text, { dimColor: true, children: "loading this project's tables\u2026" })) : tables.length === 0 ? (_jsx(Text, { dimColor: true, children: "No tables discovered for this project yet." })) : (tables.map((t, i) => {
701
+ const here = i === cursor;
702
+ return (_jsxs(Text, { color: t.monitored ? "green" : undefined, dimColor: !t.monitored, children: [here ? "❯ " : " ", t.monitored ? "[x]" : "[ ]", " ", t.name] }, t.id));
703
+ }))] }), tables && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 space/enter toggle watch \u00B7 esc to go back" }) }))] }));
570
704
  }
571
- // ── Phase: trust report (terminal) ───────────────────────────────────────────────
572
- export function Report({ ctx }) {
705
+ // ── Phase: home (trust report + hub menu) ────────────────────────────────────────
706
+ // The post-sign-in landing. Shows a trust report built ONLY from real backend data (no invented
707
+ // metrics) and an action menu; each action returns here when it finishes.
708
+ const HOME_MENU = [
709
+ { id: "manage", to: "manageprojects", label: "Manage projects", hint: "pick a project · onboard a new one" },
710
+ { id: "mcp", to: "mcp", label: "Install MCP for your agent", hint: "check_trust in Claude, Cursor & more" },
711
+ ];
712
+ /** A trust-report row with the label in a left-aligned dim column (matching the detect screen). */
713
+ function StatRow({ label, children }) {
714
+ return (_jsxs(Text, { children: [_jsx(Text, { dimColor: true, children: label.padEnd(16) }), children] }));
715
+ }
716
+ const plural = (n, s) => `${n} ${s}${n === 1 ? "" : "s"}`;
717
+ export function Home({ ctx, onDone }) {
573
718
  const { exit } = useApp();
574
719
  const { services, fast, interactive } = useWizard();
575
720
  const [projects, setProjects] = useState(null);
721
+ const [cursor, setCursor] = useState(0);
576
722
  useEffect(() => {
577
723
  let on = true;
578
724
  (async () => {
@@ -583,15 +729,15 @@ export function Report({ ctx }) {
583
729
  }
584
730
  catch {
585
731
  if (on)
586
- setProjects([]); // fall back to the trust lines only
732
+ setProjects([]); // no projects yet / offline — render the empty-state + menu
587
733
  }
588
734
  })();
589
735
  return () => {
590
736
  on = false;
591
737
  };
592
738
  }, []);
593
- // Non-interactive (demo/CI): auto-exit after a readable pause. Interactive: wait for enter so the report
594
- // doesn't flash past before it can be read.
739
+ // Non-interactive (demo/CI): the hub is terminal — there's no menu to drive, so show the report
740
+ // and exit after a readable pause.
595
741
  useEffect(() => {
596
742
  if (interactive)
597
743
  return;
@@ -599,8 +745,24 @@ export function Report({ ctx }) {
599
745
  return () => clearTimeout(t);
600
746
  }, [interactive]);
601
747
  useInput((_i, key) => {
602
- if (key.return)
603
- exit();
604
- }, { isActive: interactive });
605
- return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Text, { color: "green", bold: true, children: "\u25E7 Setup complete" }), _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsx(Text, { bold: true, children: "Sodabase is watching \u2713" }), projects === null ? (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "loading your projects\u2026" }) })) : projects.length > 0 ? (_jsx(Box, { marginTop: 1, children: _jsx(WatchedProjects, { projects: projects }) })) : null, _jsxs(Box, { marginTop: 1, flexDirection: "column", children: [_jsxs(Text, { children: [" ", "Access ", _jsx(Text, { bold: true, children: "read-only" }), " ", _jsx(Text, { dimColor: true, children: "\u00B7 scoped soda_readonly role \u00B7 audited" })] }), _jsxs(Text, { children: [" ", "Baselines ", _jsx(Text, { dimColor: true, children: "warming up \u2014 alerts stay quiet for the first 24h" })] }), ctx.installed && ctx.installed.length > 0 && (_jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "\u2714" }), " MCP installed for ", ctx.installed.join(", "), " ", _jsx(Text, { dimColor: true, children: "\u00B7 check_trust next restart" })] }))] }), _jsxs(Box, { marginTop: 1, children: [_jsx(Text, { dimColor: true, children: "Dashboard \u2192 " }), _jsxs(Text, { color: "cyan", children: ["https://sodabase.io/projects/", ctx.projectRef ?? "…"] })] }), interactive && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "enter to finish" }) }))] })] }));
748
+ if (key.upArrow)
749
+ setCursor((c) => Math.max(0, c - 1));
750
+ else if (key.downArrow)
751
+ setCursor((c) => Math.min(HOME_MENU.length - 1, c + 1));
752
+ else if (key.return) {
753
+ const item = HOME_MENU[cursor];
754
+ if (item)
755
+ onDone({}, { to: item.to });
756
+ }
757
+ }, { isActive: interactive && projects !== null });
758
+ const list = projects ?? [];
759
+ const watching = list.length > 0;
760
+ const tables = list.reduce((a, p) => a + p.watched, 0);
761
+ const findings = list.reduce((a, p) => a + p.dataQualityIssues, 0);
762
+ const signals = list.reduce((a, p) => a + p.openIssues, 0);
763
+ const healthy = list.filter((p) => totalIssues(p) === 0).length;
764
+ return (_jsxs(Box, { flexDirection: "column", paddingX: 2, marginTop: 1, children: [_jsx(Eyebrow, { children: watching ? "Sodabase is watching" : "Welcome to Sodabase" }), _jsx(Box, { marginTop: 1, flexDirection: "column", children: projects === null ? (_jsx(Text, { dimColor: true, children: "loading your trust report\u2026" })) : watching ? (_jsxs(_Fragment, { children: [_jsxs(StatRow, { label: "Tables watched", children: [_jsx(Text, { color: "green", bold: true, children: tables }), " ", "across ", plural(list.length, "project")] }), _jsxs(StatRow, { label: "Day-1 findings", children: [_jsx(Text, { color: findings > 0 ? "yellow" : "green", bold: true, children: findings }), " ", "to review", healthy > 0 && _jsxs(Text, { dimColor: true, children: [" \u00B7 ", plural(healthy, "project"), " healthy"] })] }), _jsxs(StatRow, { label: "Open signals", children: [_jsx(Text, { color: signals > 0 ? "yellow" : "green", bold: true, children: signals }), " ", _jsx(Text, { dimColor: true, children: "freshness & volume anomalies" })] }), ctx.installed && ctx.installed.length > 0 && (_jsxs(StatRow, { label: "MCP", children: [_jsx(Text, { color: "green", children: "\u2714" }), " installed for ", ctx.installed.join(", ")] }))] })) : (_jsxs(_Fragment, { children: [_jsx(Text, { children: "You're not watching any projects yet." }), _jsx(Text, { dimColor: true, children: "Pick one below \u2014 Sodabase sets up read-only monitoring, no code changes." })] })) }), interactive && projects !== null && (_jsxs(_Fragment, { children: [_jsx(Box, { marginTop: 1, flexDirection: "column", children: HOME_MENU.map((m, i) => {
765
+ const here = i === cursor;
766
+ return (_jsxs(Text, { color: here ? "green" : undefined, children: [here ? "❯ " : " ", m.label, " ", _jsxs(Text, { dimColor: true, children: ["\u00B7 ", m.hint] })] }, m.id));
767
+ }) }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { dimColor: true, children: "\u2191\u2193 move \u00B7 enter select \u00B7 esc to quit" }) })] }))] }));
606
768
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sodabase",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "Sodabase onboarding wizard — v2 interactive CLI (npx sodabase).",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://sodabase.io",
@@ -1,45 +0,0 @@
1
- // Lightweight resume state. The server already makes the work idempotent (connect
2
- // provisioning is guarded by the connect state machine; the onboarding job has a unique
3
- // index per connection, so re-starting attaches to the same run). So this is only a UX
4
- // convenience — re-enter the flow where you left off instead of from the top. A 0600
5
- // file next to the credentials; safe to delete.
6
- import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
- import { homedir } from "node:os";
8
- import { dirname, join } from "node:path";
9
- const MAX_AGE_MS = 24 * 60 * 60 * 1000; // ignore stale progress after a day
10
- function progressPath() {
11
- const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
12
- return join(base, "sodabase", "progress.json");
13
- }
14
- export function loadProgress() {
15
- try {
16
- const p = JSON.parse(readFileSync(progressPath(), "utf8"));
17
- if (!p.phase || typeof p.updatedAt !== "number")
18
- return null;
19
- if (Date.now() - p.updatedAt > MAX_AGE_MS)
20
- return null; // too old to trust
21
- return p;
22
- }
23
- catch {
24
- return null;
25
- }
26
- }
27
- export function saveProgress(p) {
28
- try {
29
- const path = progressPath();
30
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
31
- writeFileSync(path, JSON.stringify({ ...p, updatedAt: Date.now() }, null, 2), { mode: 0o600 });
32
- chmodSync(path, 0o600);
33
- }
34
- catch {
35
- /* non-fatal — resume is a convenience */
36
- }
37
- }
38
- export function clearProgress() {
39
- try {
40
- rmSync(progressPath());
41
- }
42
- catch {
43
- /* already gone */
44
- }
45
- }