Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions apps/cli/docs/supabase-home.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Managed stack documents and runtime artifacts are shared through the global CLI
<SUPABASE_HOME>/
access-token
cli-latest
stack-nudge.json
telemetry.json
bin/
stacks/
Expand Down Expand Up @@ -140,6 +141,13 @@ subdirectory they use `<SUPABASE_HOME>/cli-latest`. A failed fetch writes an emp
suppresses the notice and further fetches until it expires. The cache is skipped when the file,
`supabase/.temp`, or `SUPABASE_HOME` is a symlink. `SUPABASE_NO_UPDATE_NOTIFIER=1` disables the check.

## Local stack nudge

On the legacy backend, `supabase start` suggests trying the experimental local stack at most once
every seven days. It records the last time it showed the suggestion as `{"lastShownAt": <epoch ms>}`
in `<SUPABASE_HOME>/stack-nudge.json`. A missing, unreadable, or future timestamp shows the
suggestion again, and a failed write never fails `start`.

## Related docs

- [CLI Code Structure](./code-structure.md)
Expand Down
15 changes: 14 additions & 1 deletion apps/cli/src/command-internal/agent-mode.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { Option } from "effect";
import { Effect, Option } from "effect";

import { AiTool } from "../shared/telemetry/ai-tool.service.ts";
import { AgentFlag } from "./global-flags.ts";

/** Agent-mode resolution: `yes`→true, `no`→false, `auto`→agent detected. */
export function resolveAgentMode(
Expand All @@ -9,3 +12,13 @@ export function resolveAgentMode(
if (agentFlag === "no") return false;
return Option.isSome(aiToolName);
}

/** Whether `--agent` or a detected AI tool marks this run as driven by a coding agent. */
export const agentDetected = Effect.gen(function* () {
const flag = Option.getOrElse(yield* Effect.serviceOption(AgentFlag), () => "auto" as const);
const tool = yield* Effect.serviceOption(AiTool);
return resolveAgentMode(
flag,
Option.flatMap(tool, (detected) => detected.name),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,15 @@ import { Effect, Option } from "effect";

import { Output } from "../../shared/output/output.service.ts";
import { isMachineResourceFormat } from "../../shared/output/resource-format.ts";
import { AiTool } from "../../shared/telemetry/ai-tool.service.ts";
import { Tty } from "../../shared/runtime/tty.service.ts";
import { resolveAgentMode } from "../agent-mode.ts";
import { AgentFlag, OutputFlag } from "../global-flags.ts";
import { agentDetected } from "../agent-mode.ts";
import { OutputFlag } from "../global-flags.ts";

export interface PromptBlocker {
readonly reason: string;
readonly agent: boolean;
}

const agentDetected = Effect.gen(function* () {
const flag = Option.getOrElse(yield* Effect.serviceOption(AgentFlag), () => "auto" as const);
const tool = yield* Effect.serviceOption(AiTool);
return resolveAgentMode(
flag,
Option.flatMap(tool, (detected) => detected.name),
);
});

/**
* Why this run cannot ask a question, or `None` when it can: text output on an interactive
* stdout with a TTY stdin, no machine `-o` format, and no agent driving it.
Expand Down
103 changes: 103 additions & 0 deletions apps/cli/src/command-internal/stack-nudge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { Clock, Effect, FileSystem, Path, Schema } from "effect";

import { CommandSettings } from "../config/command-settings.service.ts";
import { resolveExperimentalFeature } from "../shared/config/experimental-feature.ts";
import { Output } from "../shared/output/output.service.ts";
import { agentDetected } from "./agent-mode.ts";

const DOCS_URL =
"https://supabase.com/docs/guides/local-development/running-multiple-local-projects";

const START_STACK_NUDGE_MESSAGE = `Try the new local stack: faster, lighter, and one project per worktree in parallel.
To switch: remove the fixed ports from supabase/config.toml, then add \`stack = true\` under \`[experimental]\`.
Steps and limitations: ${DOCS_URL}`;

const INIT_STACK_NUDGE_MESSAGE = `Try the new faster, lighter, parallel local stack: set SUPABASE_EXPERIMENTAL_STACK=1 before your next \`supabase init\`.
To switch this project: ${DOCS_URL}`;

const INIT_STACK_ENABLED_MESSAGE =
"Experimental local stack enabled in supabase/config.toml. Share feedback: https://github.com/supabase/cli/issues";

const NUDGE_STATE_FILE = "stack-nudge.json";
Comment thread
avallete marked this conversation as resolved.
Resolved
const NUDGE_INTERVAL_MILLIS = 7 * 24 * 60 * 60 * 1000;

const NudgeState = Schema.fromJsonString(Schema.Struct({ lastShownAt: Schema.Finite }));

const START_AGENT_ASK_LINE =
"Coding agents: offer this switch to the user and ask before changing supabase/config.toml.";
const INIT_AGENT_ASK_LINE =
"Coding agents: offer this to the user and ask before changing supabase/config.toml.";

/**
* Who to nudge: a coding agent, a human at a terminal, or nobody. Text mode writes to stderr so
* piped stdout stays clean; json and stream-json use `output.info` so result payloads are unchanged.
*/
const nudgeAudience = Effect.gen(function* () {
const output = yield* Output;
// With the config side pinned to true, only an explicit shell `SUPABASE_EXPERIMENTAL_STACK=0`
// resolves to false; that user opted out, so the nudge stays quiet.
const optedOut = !(yield* resolveExperimentalFeature({
feature: "stack",
configValue: Effect.succeed(true),
}).pipe(Effect.orElseSucceed(() => true)));
if (optedOut) return undefined;
if (yield* agentDetected) return "agent" as const;
return output.interactive ? ("human" as const) : undefined;
});
Comment thread
avallete marked this conversation as resolved.
Resolved

const emitNudge = Effect.fnUntraced(function* (message: string) {
const output = yield* Output;
if (output.format === "text") return yield* output.raw(`${message}\n`, "stderr");
return yield* output.info(message);
});

/**
* Prints the stack nudge on stderr at most once every 7 days. The throttle state is best-effort:
* any read or write failure is swallowed so it can never fail `start`.
*/
export const maybeShowStartStackNudge = Effect.fn("StackNudge.maybeShowStart")(function* () {
const audience = yield* nudgeAudience;
if (audience === undefined) return;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const settings = yield* CommandSettings;
const statePath = path.join(settings.supabaseHome, NUDGE_STATE_FILE);
const now = yield* Clock.currentTimeMillis;

const lastShownAt = yield* fs.readFileString(statePath).pipe(
Effect.flatMap(Schema.decodeUnknownEffect(NudgeState)),
Effect.map((state) => state.lastShownAt),
Effect.orElseSucceed(() => undefined),
);
const throttled =
lastShownAt !== undefined &&
now - lastShownAt >= 0 &&
now - lastShownAt < NUDGE_INTERVAL_MILLIS;
yield* Effect.annotateCurrentSpan({ "stack_nudge.throttled": throttled });
if (throttled) return;

yield* emitNudge(
audience === "agent"
? `${START_STACK_NUDGE_MESSAGE}\n${START_AGENT_ASK_LINE}`
: START_STACK_NUDGE_MESSAGE,
);
yield* Effect.gen(function* () {
const encoded = yield* Schema.encodeEffect(NudgeState)({ lastShownAt: now });
yield* fs.makeDirectory(settings.supabaseHome, { recursive: true, mode: 0o700 });
yield* fs.writeFileString(statePath, encoded);
Comment on lines +67 to +87

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MINOR · concurrency · source: codex

Concurrent starts that share a Supabase home can both show the hint within the seven-day cooldown.

Evidence: apps/cli/src/command-internal/stack-nudge.ts:55–56 builds a shared state path. Lines 59–69 read and check the timestamp, lines 71–75 emit the hint, and lines 76–80 write the timestamp. No interprocess synchronization covers those operations.

Suggested fix: Use a per-home lock to serialize the cooldown check, emission, and timestamp update. Keep lock and state failures from failing start.

}).pipe(Effect.ignore);
});

/** Prints the `init` nudge or confirmation on stderr to a human at a terminal or an agent. */
export const showInitStackNote = Effect.fn("StackNudge.showInit")(function* (
experimentalStack: boolean,
) {
const audience = yield* nudgeAudience;
if (audience === undefined) return;
if (experimentalStack) return yield* emitNudge(INIT_STACK_ENABLED_MESSAGE);
yield* emitNudge(
audience === "agent"
? `${INIT_STACK_NUDGE_MESSAGE}\n${INIT_AGENT_ASK_LINE}`
: INIT_STACK_NUDGE_MESSAGE,
);
});
2 changes: 2 additions & 0 deletions apps/cli/src/commands/init/init.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { initProject } from "../../shared/init/project-init.ts";
import { Output } from "../../shared/output/output.service.ts";
import { resolveExperimentalFeature } from "../../shared/config/experimental-feature.ts";
import { WorkdirFlag, resolveYes } from "../../command-internal/global-flags.ts";
import { showInitStackNote } from "../../command-internal/stack-nudge.ts";
import { InitConfigExistsError } from "./init.errors.ts";
import type { InitFlags } from "./init.command.ts";

Expand Down Expand Up @@ -53,4 +54,5 @@ export const init = Effect.fn("init")(function* (flags: InitFlags) {
}

yield* output.raw("Finished supabase init.\n");
yield* showInitStackNote(experimentalStack);
});
59 changes: 58 additions & 1 deletion apps/cli/src/commands/init/init.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ import {
Stdio,
} from "effect";
import { CliArgs } from "../../shared/cli/cli-args.service.ts";
import { ExperimentalFlag, WorkdirFlag, YesFlag } from "../../command-internal/global-flags.ts";
import {
AgentFlag,
ExperimentalFlag,
WorkdirFlag,
YesFlag,
} from "../../command-internal/global-flags.ts";
import { normalizeCause } from "../../shared/output/normalize-error.ts";
import { textOutputLayer } from "../../shared/output/output.layer.ts";
import { Output } from "../../shared/output/output.service.ts";
Expand Down Expand Up @@ -527,6 +532,58 @@ describe("init", () => {
});
});

it.effect.each([
{
env: {},
interactive: true,
expected: "set SUPABASE_EXPERIMENTAL_STACK=1 before your next `supabase init`",
},
{
env: { SUPABASE_EXPERIMENTAL_STACK: "1" },
interactive: true,
expected: "Experimental local stack enabled in supabase/config.toml",
},
{ env: {}, interactive: false, expected: undefined },
{ env: { SUPABASE_EXPERIMENTAL_STACK: "0" }, interactive: true, expected: undefined },
{
env: {},
interactive: false,
agent: true,
expected:
"Coding agents: offer this to the user and ask before changing supabase/config.toml",
},
])(
"stack note (interactive=$interactive, agent=$agent, env=$env)",
({ env, interactive, agent, expected }) => {
const tempDir = tempRoot.current;

return Effect.gen(function* () {
const { layer, out } = setup(tempDir, { env, interactive });

yield* init({
interactive: false,
useOrioledb: false,
force: false,
withVscodeWorkspace: false,
withVscodeSettings: false,
withIntellijSettings: false,
}).pipe(
Effect.provide(
agent === true
? Layer.mergeAll(layer, Layer.succeed(AgentFlag, "yes" as const))
: layer,
),
);

if (expected === undefined) {
expect(out.stderrText).not.toContain("local stack");
} else {
expect(out.stderrText).toContain(expected);
}
});
},
);

it.effect("keeps the established template when SUPABASE_EXPERIMENTAL_STACK=0", () => {
const tempDir = tempRoot.current;

Expand Down
3 changes: 3 additions & 0 deletions apps/cli/src/commands/start/start.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ import {
StatusListError,
} from "../../command-internal/status-errors.ts";
import { renderStatusPretty } from "../../command-internal/status-pretty.ts";
import { maybeShowStartStackNudge } from "../../command-internal/stack-nudge.ts";
import {
gateStatusState,
resolveStatusLocalState,
Expand Down Expand Up @@ -1660,8 +1661,10 @@ export const start = Effect.fn("start")(function* (flags: StartFlags) {
const { values: statusValues, names } = yield* buildStatusValues(statusExcluded, values);
yield* output.raw(renderStatusPretty(statusValues, names));
yield* output.raw(startSecurityNotice(), "stderr");
if (!flags.ignoreHealthCheck) yield* maybeShowStartStackNudge();
} else {
const { values: statusValues } = yield* buildStatusValues(statusExcluded, values);
if (!flags.ignoreHealthCheck) yield* maybeShowStartStackNudge();
yield* output.success("", statusValues);
}
}).pipe(Effect.scoped, Effect.ensuring(telemetryState.flush));
Expand Down
54 changes: 53 additions & 1 deletion apps/cli/src/commands/start/start.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
classifyCliErrorActionability,
} from "../../shared/telemetry/error-actionability.ts";
import {
AgentFlag,
DebugFlag,
ExperimentalFlag,
NetworkIdFlag,
Expand Down Expand Up @@ -643,6 +644,8 @@ interface SetupOpts {
readonly networkId?: Option.Option<string>;
/** `--experimental`/`SUPABASE_EXPERIMENTAL`. Defaults to `false`. */
readonly experimental?: boolean;
/** Stdout is a terminal. Defaults to `false`. */
readonly interactive?: boolean;
/** Replaces the `DbConnection.connect` behind the Postgres readiness probe. Defaults to succeeding. */
readonly dbConnect?: (typeof DbConnection)["Service"]["connect"];
}
Expand All @@ -655,7 +658,7 @@ const setup = Effect.fnUntraced(function* (opts: SetupOpts = {}) {
opts.configContents ?? `project_id = "${opts.configuredProjectId ?? "demo"}"\n`,
);
}
const out = mockOutput({ format: opts.format ?? "text" });
const out = mockOutput({ format: opts.format ?? "text", interactive: opts.interactive });
const telemetry = mockTelemetryStateTracked();
const analytics = mockAnalytics();
const cliSettings = mockCommandSettings({ workdir });
Expand Down Expand Up @@ -1960,6 +1963,55 @@ describe("start integration", () => {
}).pipe(Effect.provide([BunServices.layer, BunCrypto.layer])),
);

describe("stack nudge", () => {
const NUDGE = "Try the new local stack";
const nudgeShown = Effect.fnUntraced(function* () {
const { layer, out } = yield* setup({ interactive: true });
yield* start(flags()).pipe(Effect.provide(layer));
return out.stderrText.includes(NUDGE);
});

it.effect("shows the nudge on stderr again only after 7 days", () =>
Effect.gen(function* () {
expect(yield* nudgeShown()).toBe(true);

yield* TestClock.adjust(7 * 24 * 60 * 60 * 1000 - 1);
expect(yield* nudgeShown()).toBe(false);

yield* TestClock.adjust("1 millis");
expect(yield* nudgeShown()).toBe(true);
}).pipe(Effect.provide([BunServices.layer, BunCrypto.layer])),
);

it.effect("stays silent when stdout is not a terminal", () =>
Effect.gen(function* () {
const { layer, out } = yield* setup({ interactive: false });
yield* start(flags()).pipe(Effect.provide(layer));
expect(out.stderrText).not.toContain(NUDGE);
}).pipe(Effect.provide([BunServices.layer, BunCrypto.layer])),
);

it.effect(
"emits the nudge to an agent in json mode without changing the result payload",
() =>
Effect.gen(function* () {
const { layer, out } = yield* setup({ format: "json", interactive: false });
yield* start(flags()).pipe(
Effect.provide(Layer.mergeAll(layer, Layer.succeed(AgentFlag, "yes" as const))),
);
const info = out.messages
.filter((m) => m.type === "info")
.map((m) => m.message)
.join("\n");
expect(info).toContain(NUDGE);
expect(info).toContain("Coding agents: offer this switch to the user");
expect(out.messages.find((m) => m.type === "success")?.data).toMatchObject({
DB_URL: expect.any(String),
});
Comment on lines +2008 to +2010

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MINOR · test-coverage · source: codex

The agent JSON test would pass if the hint also appeared in the success payload or if status fields other than DB_URL disappeared.

Evidence: apps/cli/src/commands/start/start.integration.test.ts:1995 names payload preservation as part of the test. Lines 2002–2007 check the info message separately, and lines 2008–2010 use a partial object match that requires only DB_URL.

Suggested fix: Assert the complete expected success payload for the fixture and keep the separate info-message assertion.

}).pipe(Effect.provide([BunServices.layer, BunCrypto.layer])),
);
});

it.effect("emits a machine status payload in json mode instead of the pretty table", () =>
Effect.gen(function* () {
const { layer, out } = yield* setup({ format: "json" });
Expand Down
Loading