Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: crbn up --borrow, realtime retry + toast, hydrate fixes (#779)

yidongwbae0497ca2cc
diff --git a/apps/academy/app/routes/_auth+/login.tsx b/apps/academy/app/routes/_auth+/login.tsx
index f16586926a..72294f8adf 100644
--- a/apps/academy/app/routes/_auth+/login.tsx
+++ b/apps/academy/app/routes/_auth+/login.tsx
@@ -54,15 +54,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
};
}
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
- analytics: true
-});
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
+ analytics: true
+ });
const { success } = await ratelimit.limit(ip);
if (!success) {
diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsx
index 70774864cc..bd75fc5443 100644
--- a/apps/erp/app/components/Form/Item.tsx
+++ b/apps/erp/app/components/Form/Item.tsx
@@ -103,7 +103,6 @@ const Item = ({
const translateItemType = useTranslatedItemType();
const [items] = useItems();
- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
const options = useMemo(() => {
let results = items
.filter((item) => {
@@ -160,7 +159,8 @@ const Item = ({
props.locationId,
props.replenishmentSystem,
props.whitelist,
- type
+ type,
+ validItemTypes
]);
const selectTypeModal = useDisclosure();
diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsx
index 1c5663ecc6..697f4d8c1f 100644
--- a/apps/erp/app/components/RealtimeDataProvider.tsx
+++ b/apps/erp/app/components/RealtimeDataProvider.tsx
@@ -23,6 +23,11 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
hydratedFromServer = false;
}, [companyId]);
+ // Reset on logout so the next login triggers a fresh server hydrate.
+ useEffect(() => {
+ if (!accessToken) hydratedFromServer = false;
+ }, [accessToken]);
+
const [, setItems] = useItems();
const [, setSuppliers] = useSuppliers();
const [, setCustomers] = useCustomers();
@@ -154,24 +159,27 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
setItems(items.data ?? []);
setSuppliers(suppliers.data ?? []);
setCustomers(customers.data ?? []);
- setPeople(
- // @ts-ignore
- people.data ?? []
- );
+ // @ts-ignore
+ setPeople(people.data ?? []);
- idb.setItem("items", items.data);
- idb.setItem("suppliers", suppliers.data);
- idb.setItem("customers", customers.data);
- idb.setItem("people", people.data);
+ await Promise.all([
+ idb.setItem("items", items.data),
+ idb.setItem("suppliers", suppliers.data),
+ idb.setItem("customers", customers.data),
+ idb.setItem("people", people.data)
+ ]);
fetchQuantities();
};
- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
+ // Re-run when auth becomes ready: `hydrate()` bails if `carbon` / `accessToken` are missing,
+ // and with only `[companyId]` that first run could be the only attempt — leaving `items` empty
+ // (e.g. New Job item combobox shows no options).
+ // biome-ignore lint/correctness/useExhaustiveDependencies: hydrate closes over setters + idb
useEffect(() => {
if (!companyId) return;
- hydrate();
- }, [companyId]);
+ hydrate().catch((err) => console.error("hydrate failed:", err));
+ }, [companyId, carbon, accessToken]);
useInterval(fetchQuantities, companyId ? 10 * 60 * 1000 : null);
@@ -217,7 +225,6 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
)
)
);
-
break;
case "UPDATE":
const { new: updated } = payload;
diff --git a/apps/erp/app/routes/[.well-known]+/$.tsx b/apps/erp/app/routes/[.well-known]+/$.tsx
new file mode 100644
index 0000000000..b63acd7ffe
--- /dev/null
+++ b/apps/erp/app/routes/[.well-known]+/$.tsx
@@ -0,0 +1,5 @@
+import { data } from "react-router";
+
+export function loader() {
+ return data(null, { status: 404 });
+}
diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsx
index f875a1f5c0..bd6175bd6f 100644
--- a/apps/erp/app/routes/_public+/login.tsx
+++ b/apps/erp/app/routes/_public+/login.tsx
@@ -10,11 +10,16 @@ import {
magicLinkValidator,
RATE_LIMIT
} from "@carbon/auth";
-import { sendMagicLink, verifyAuthSession } from "@carbon/auth/auth.server";
+import {
+ sendMagicLink,
+ signInWithBypassEmail,
+ verifyAuthSession
+} from "@carbon/auth/auth.server";
import {
clearAuthCookies,
flash,
- getAuthSession
+ getAuthSession,
+ setAuthSession
} from "@carbon/auth/session.server";
import { getUserByEmail } from "@carbon/auth/users.server";
import { sendVerificationCode } from "@carbon/auth/verification.server";
@@ -72,15 +77,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
return { providers: AUTH_PROVIDERS.split(",") };
}
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
- analytics: true
-});
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
+ analytics: true
+ });
const { success } = await ratelimit.limit(ip);
if (!success) {
@@ -133,6 +137,21 @@ export async function action({ request }: ActionFunctionArgs) {
const user = await getUserByEmail(email);
+ const devBypassEmail = process.env.DEV_BYPASS_EMAIL;
+ if (
+ devBypassEmail &&
+ email.toLowerCase() === devBypassEmail.toLowerCase() &&
+ user.data?.active
+ ) {
+ const authSession = await signInWithBypassEmail(email);
+ if (authSession) {
+ const sessionCookie = await setAuthSession(request, { authSession });
+ return redirect(path.to.authenticatedRoot, {
+ headers: [["Set-Cookie", sessionCookie]]
+ });
+ }
+ }
+
if (user.data && user.data.active) {
const magicLink = await sendMagicLink(email);
diff --git a/apps/erp/app/routes/_public+/verify.tsx b/apps/erp/app/routes/_public+/verify.tsx
index abf11e5482..1b754d362a 100644
--- a/apps/erp/app/routes/_public+/verify.tsx
+++ b/apps/erp/app/routes/_public+/verify.tsx
@@ -58,16 +58,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
return null;
}
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
- analytics: true
-});
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
+ analytics: true
+ });
+
const { success } = await ratelimit.limit(ip);
if (!success) {
diff --git a/apps/erp/app/routes/api+/docs.ts b/apps/erp/app/routes/api+/docs.ts
index 1a26076dff..a89254a5c2 100644
--- a/apps/erp/app/routes/api+/docs.ts
+++ b/apps/erp/app/routes/api+/docs.ts
@@ -7,14 +7,13 @@ import {
} from "react-router";
import { docsQuery } from "~/utils/react-query";
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(20, "1 h"),
- analytics: true
-});
-
export async function loader({ request }: LoaderFunctionArgs) {
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(20, "1 h"),
+ analytics: true
+ });
const { success } = await ratelimit.limit(`docs:${ip}`);
if (!success) {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tools/accounting.ts b/apps/erp/app/routes/api+/mcp+/lib/tools/accounting.ts
index adc534b7c1..659d2d5574 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tools/accounting.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/tools/accounting.ts
@@ -1213,7 +1213,6 @@ export const registerAccountingTools: RegisterTools = (server, ctx) => {
description: z.string().optional(),
lines: z.any(),
accountId: z.string(),
- description: z.string().optional(),
debit: z.number(),
credit: z.number(),
dimensions: z.any().optional(),
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index c58419e99b..1562213fdc 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -35,12 +35,6 @@ const supportedFileTypes: Record<string, string> = {
step: "application/step"
};
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(10, "1 m"), // 10 downloads per minute
- analytics: true
-});
-
export let loader = async ({ params, request }: LoaderFunctionArgs) => {
const { id } = params;
if (!id) {
@@ -48,7 +42,11 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {
}
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
-
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(10, "1 m"), // 10 downloads per minute
+ analytics: true
+ });
const { success } = await ratelimit.limit(ip);
if (!success) {
diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsx
index 8783cb76ea..4398a61b09 100644
--- a/apps/mes/app/routes/_public+/login.tsx
+++ b/apps/mes/app/routes/_public+/login.tsx
@@ -66,15 +66,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
return { providers: AUTH_PROVIDERS.split(",") };
}
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
- analytics: true
-});
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
+ analytics: true
+ });
const { success } = await ratelimit.limit(ip);
if (!success) {
diff --git a/apps/starter/app/routes/_public+/login.tsx b/apps/starter/app/routes/_public+/login.tsx
index 55cca2044a..5ef713af4f 100644
--- a/apps/starter/app/routes/_public+/login.tsx
+++ b/apps/starter/app/routes/_public+/login.tsx
@@ -54,15 +54,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
};
}
-const ratelimit = new Ratelimit({
- redis,
- limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
- analytics: true
-});
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const ip = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
+ const ratelimit = new Ratelimit({
+ redis,
+ limiter: Ratelimit.slidingWindow(RATE_LIMIT, "1 h"),
+ analytics: true
+ });
const { success } = await ratelimit.limit(ip);
if (!success) {
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index d85369615b..d597f53df1 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -60,9 +60,11 @@ services:
GOTRUE_JWT_AUD: authenticated
GOTRUE_EXTERNAL_EMAIL_ENABLED: "true"
GOTRUE_MAILER_AUTOCONFIRM: "true"
- GOTRUE_SMTP_HOST: inbucket
- GOTRUE_SMTP_PORT: 2500
- GOTRUE_SMTP_ADMIN_EMAIL: [email protected]
+ GOTRUE_SMTP_HOST: ${GOTRUE_SMTP_HOST:-inbucket}
+ GOTRUE_SMTP_PORT: ${GOTRUE_SMTP_PORT:-2500}
+ GOTRUE_SMTP_USER: ${GOTRUE_SMTP_USER:-}
+ GOTRUE_SMTP_PASS: ${GOTRUE_SMTP_PASS:-}
+ GOTRUE_SMTP_ADMIN_EMAIL: ${GOTRUE_SMTP_ADMIN_EMAIL:[email protected]}
GOTRUE_SMTP_SENDER_NAME: Carbon
GOTRUE_EXTERNAL_GOOGLE_ENABLED: "true"
GOTRUE_EXTERNAL_GOOGLE_CLIENT_ID: ${SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID:-}
@@ -105,6 +107,10 @@ services:
depends_on:
postgres:
condition: service_healthy
+ networks:
+ default:
+ aliases:
+ - realtime-dev
environment:
PORT: 4000
DB_HOST: postgres
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index 084ddc7a5c..3a9b3acafe 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -388,7 +388,7 @@ export async function sendInviteByEmail(
data?: Record<string, unknown>
) {
return getCarbonServiceRole().auth.admin.inviteUserByEmail(email, {
- redirectTo: `${VERCEL_URL}`,
+ redirectTo: `${VERCEL_URL}/callback`,
data
});
}
@@ -397,11 +397,44 @@ export async function sendMagicLink(email: string) {
return getCarbonServiceRole().auth.signInWithOtp({
email,
options: {
- emailRedirectTo: `${VERCEL_URL}`
+ emailRedirectTo: `${VERCEL_URL}/callback`
}
});
}
+export async function signInWithBypassEmail(
+ email: string
+): Promise<AuthSession | null> {
+ const client = getCarbonServiceRole();
+
+ const { data: linkData, error: linkError } =
+ await client.auth.admin.generateLink({ type: "magiclink", email });
+
+ if (linkError || !linkData?.properties?.hashed_token) return null;
+
+ const { data: sessionData, error: verifyError } = await client.auth.verifyOtp(
+ { token_hash: linkData.properties.hashed_token, type: "magiclink" }
+ );
+
+ if (verifyError || !sessionData?.session) return null;
+
+ const companies = await getCompaniesForUser(
+ client,
+ sessionData.session.user.id
+ );
+ const { data: companyRecord } = await client
+ .from("company")
+ .select("companyGroupId")
+ .eq("id", companies?.[0] ?? "")
+ .single();
+
+ return makeAuthSession(
+ sessionData.session,
+ companies?.[0] ?? "",
+ companyRecord?.companyGroupId ?? ""
+ );
+}
+
export async function signInWithEmail(email: string, password: string) {
const client = getCarbonServiceRole();
const { data, error } = await client.auth.signInWithPassword({
diff --git a/packages/dev/docker/kong.yml b/packages/dev/docker/kong.yml
index 3b77d18398..0590797f78 100644
--- a/packages/dev/docker/kong.yml
+++ b/packages/dev/docker/kong.yml
@@ -7,6 +7,16 @@ _transform: true
###
services:
+ - name: auth-verify
+ url: http://gotrue:9999/verify
+ routes:
+ - name: auth-verify
+ strip_path: true
+ paths:
+ - /verify
+ plugins:
+ - name: cors
+
- name: auth-v1-open
url: http://gotrue:9999/verify
routes:
@@ -58,7 +68,7 @@ services:
- name: cors
- name: realtime-v1-ws
- url: http://realtime:4000/socket
+ url: http://realtime-dev:4000/socket
protocol: ws
routes:
- name: realtime-v1-ws
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index 9ff09d21ca..c1733d8c5a 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -6,7 +6,7 @@ import type { AppId } from "../constants.js";
import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";
import { currentBranch, isLinkedWorktree } from "../git.js";
import { onShutdown } from "../helpers.js";
-import { pickApps } from "../prompts.js";
+import { pickApps, pickBorrowSlug } from "../prompts.js";
import {
installDeps,
spawnApps,
@@ -48,6 +48,7 @@ import {
import { summaryLines } from "../ui.js";
import {
ensureSlugAvailable,
+ getSlot,
getWorktreeRoot,
type JwtCreds,
type PortMap,
@@ -66,6 +67,8 @@ type UpOpts = {
apps?: boolean;
/** When true, always `docker compose pull` even if images exist locally. */
pull?: boolean;
+ /** When true, show a picker to borrow another worktree's running containers. */
+ borrow?: boolean;
};
type Ctx = {
@@ -82,34 +85,71 @@ export async function up(opts: UpOpts = {}) {
// Type/swagger regen depends on a freshly-migrated schema. If migrations
// were skipped, schema is unchanged — skip regen too.
const shouldRegen = shouldMigrate && (opts.regen ?? true);
+ const shouldBorrow = opts.borrow === true;
// Services-only mode: boot compose stack + portless aliases (api/studio/
// mail/inngest URLs still useful), skip spawnApps + auto-`down` on Ctrl+C.
// Triggered by --no-apps OR by deselecting everything in the picker.
const appsRequested = opts.apps ?? true;
+ // Load .env early so CARBON_PORTLESS (and other flags) can be set there
+ // rather than requiring a shell export. .env.local takes precedence.
+ const root = await getWorktreeRoot();
+ loadDotenv({ path: join(root, ".env.local"), override: false });
+ loadDotenv({ path: join(root, ".env"), override: false });
+
+ // Set CARBON_PORTLESS=0 to use http://localhost:PORT URLs and skip the
+ // portless proxy setup (useful when the .dev TLD cert is not trusted).
+ const portless = process.env.CARBON_PORTLESS !== "0";
+
intro("Carbon · dev up");
- await ensurePortlessInstalled();
- await ensureProxyPrivileges();
+ if (portless) {
+ await ensurePortlessInstalled();
+ await ensureProxyPrivileges();
+ } else {
+ log.info("portless disabled (CARBON_PORTLESS=0) — using localhost URLs");
+ }
const selectedApps = appsRequested ? await pickApps() : [];
-
- const root = await getWorktreeRoot();
const slug = resolveSlug(root);
- await ensureSlugAvailable(slug, root);
+
+ // Resolve borrowed slot before ensureSlugAvailable (borrowing doesn't start
+ // own containers so the slug conflict check is irrelevant).
+ let borrowedEntry:
+ | { ports: PortMap; redisDb: number; jwt: JwtCreds }
+ | undefined;
+ if (shouldBorrow) {
+ const borrowSlug = await pickBorrowSlug(slug);
+ const entry = getSlot(borrowSlug);
+ if (!entry)
+ throw new Error(
+ `No slot found for worktree "${borrowSlug}" in ~/.carbon/dev-ports.json`
+ );
+ borrowedEntry = entry;
+ log.info(`borrowing containers from: ${borrowSlug}`);
+ } else {
+ await ensureSlugAvailable(slug, root);
+ }
+
persistSlug(root, slug);
log.info(`worktree: ${slug} (project ${projectName(slug)})`);
await refreshStaleCopyFiles(root);
await ensureDepsInstalled(root);
- const ctx = await provisionSlot(root, slug);
- await pullImages(ctx, { force: opts.pull === true });
- await bootDockerStack(ctx);
- await waitForServices(ctx);
+ const ctx = await provisionSlot(root, slug, portless, borrowedEntry);
+ if (borrowedEntry) {
+ await waitForServices(ctx);
+ } else {
+ await pullImages(ctx, { force: opts.pull === true });
+ await bootDockerStack(ctx);
+ await waitForServices(ctx);
+ }
await runDatabaseMigrations(ctx, { shouldMigrate, shouldRegen });
- await setupPortless(ctx, selectedApps);
- await ensureHostsFile();
+ if (portless) {
+ await setupPortless(ctx, selectedApps);
+ await ensureHostsFile();
+ }
if (process.env.CARBON_EDITION === "cloud") {
spawnStripeListener(root);
@@ -117,7 +157,11 @@ export async function up(opts: UpOpts = {}) {
}
box(
- summaryLines(ctx.ports, ctx.branchPrefix, selectedApps).join("\n"),
+ summaryLines(
+ ctx.ports,
+ selectedApps,
+ portless ? ctx.branchPrefix : undefined
+ ).join("\n"),
`Carbon dev — ${slug}`
);
@@ -126,7 +170,7 @@ export async function up(opts: UpOpts = {}) {
return;
}
outro("apps starting (Ctrl+C to stop)");
- await runAppsThenTeardown(root, selectedApps);
+ await runAppsThenTeardown(root, selectedApps, ctx.ports, portless);
}
// ---------------------------------------------------------------------------
@@ -154,13 +198,35 @@ async function ensureDepsInstalled(root: string) {
else log.info("pnpm install skipped (lockfile in sync)");
}
-async function provisionSlot(root: string, slug: string): Promise<Ctx> {
+async function provisionSlot(
+ root: string,
+ slug: string,
+ portless: boolean,
+ borrowedEntry?: { ports: PortMap; redisDb: number; jwt: JwtCreds }
+): Promise<Ctx> {
let ctx!: Ctx;
await tasks([
{
- title: "Configure portless",
+ title: borrowedEntry ? "Configure (borrowed slot)" : "Configure portless",
task: async () => {
- const slot = await resolveSlot(slug, root);
+ // Always resolve own slot so PORT_ERP/PORT_MES are claimed for this
+ // worktree and won't collide with the borrowed stack's running dev servers.
+ const ownSlot = await resolveSlot(slug, root);
+ const slot = borrowedEntry
+ ? {
+ // Backend ports (DB, API, Studio, Inbucket, Inngest) come from the
+ // borrowed stack — apps talk to those running containers.
+ // App ports (ERP, MES) come from our own slot — dev servers bind here,
+ // so they don't conflict with the borrowed stack's dev servers.
+ ports: {
+ ...borrowedEntry.ports,
+ PORT_ERP: ownSlot.ports.PORT_ERP,
+ PORT_MES: ownSlot.ports.PORT_MES
+ } as PortMap,
+ redisDb: borrowedEntry.redisDb,
+ jwt: borrowedEntry.jwt
+ }
+ : ownSlot;
// Prefix every non-default branch. Portless auto-prefixes only in
// linked worktrees; main checkout gets the same shape via per-app
// portless.json stamped below.
@@ -170,15 +236,21 @@ async function provisionSlot(root: string, slug: string): Promise<Ctx> {
ctx = { root, slug, branchPrefix, ...slot };
- writeEnv(root, renderEnv({ slug, branchPrefix, ...slot }));
+ writeEnv(root, renderEnv({ slug, portless, branchPrefix, ...slot }));
syncAppPortlessConfigs({
worktreeRoot: root,
- branchPrefix,
+ branchPrefix: portless ? branchPrefix : null,
linked
});
- loadDotenv({ path: join(root, ".env.local"), override: false });
+ // Use override: true so freshly written .env.local values replace any
+ // stale values already in process.env from the initial load at startup.
+ loadDotenv({ path: join(root, ".env.local"), override: true });
loadDotenv({ path: join(root, ".env"), override: false });
- return `prefix "${branchPrefix}", redis db ${slot.redisDb}`;
+ return borrowedEntry
+ ? `borrowed backend ports, own app ports (ERP :${slot.ports.PORT_ERP} MES :${slot.ports.PORT_MES}), redis db ${slot.redisDb}`
+ : portless
+ ? `prefix "${branchPrefix}", redis db ${slot.redisDb}`
+ : `localhost mode, redis db ${slot.redisDb}`;
}
},
{
@@ -368,8 +440,13 @@ async function ensureHostsFile() {
await syncHostsFile();
}
-async function runAppsThenTeardown(root: string, selectedApps: AppId[]) {
- await spawnApps({ root, apps: selectedApps });
+async function runAppsThenTeardown(
+ root: string,
+ selectedApps: AppId[],
+ ports: PortMap,
+ portless: boolean
+) {
+ await spawnApps({ root, apps: selectedApps, ports, portless });
// Apps exit on Ctrl+C; auto-`down` so compose stack isn't orphaned.
// Swallow further signals so a second Ctrl+C during teardown doesn't
diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.ts
index 7b631d6c72..fad4070a5d 100644
--- a/packages/dev/src/env.test.ts
+++ b/packages/dev/src/env.test.ts
@@ -7,7 +7,9 @@ const ports: PortMap = {
PORT_API: 54001,
PORT_STUDIO: 54002,
PORT_INBUCKET: 54003,
- PORT_INNGEST: 54004
+ PORT_INNGEST: 54004,
+ PORT_ERP: 54005,
+ PORT_MES: 54006
};
const jwt: JwtCreds = {
@@ -16,19 +18,90 @@ const jwt: JwtCreds = {
serviceKey: "test-service-key"
};
-describe("renderEnv", () => {
- it("emits the per-worktree slug and prefix-derived hosts", () => {
+describe("renderEnv (portless disabled)", () => {
+ it("emits localhost URLs for app and supabase", () => {
const out = renderEnv({
slug: "feat-x",
ports,
redisDb: 3,
jwt,
+ portless: false
+ });
+ expect(out).toContain("CARBON_WORKTREE=feat-x");
+ expect(out).toContain("ERP_URL=http://localhost:54005");
+ expect(out).toContain("MES_URL=http://localhost:54006");
+ expect(out).toContain("SUPABASE_URL=http://localhost:54001");
+ expect(out).not.toContain("PORTLESS_TLD");
+ });
+
+ it("wires every port into env vars", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ portless: false
+ });
+ expect(out).toContain("PORT_DB=54000");
+ expect(out).toContain("PORT_API=54001");
+ expect(out).toContain("PORT_STUDIO=54002");
+ expect(out).toContain("PORT_INBUCKET=54003");
+ expect(out).toContain("PORT_INNGEST=54004");
+ expect(out).toContain("PORT_ERP=54005");
+ expect(out).toContain("PORT_MES=54006");
+ });
+
+ it("places redis db index in REDIS_URL", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 7,
+ jwt,
+ portless: false
+ });
+ expect(out).toMatch(/REDIS_URL=redis:\/\/localhost:\d+\/7/);
+ });
+
+ it("injects jwt creds verbatim", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ portless: false
+ });
+ expect(out).toContain("SUPABASE_JWT_SECRET=test-secret");
+ expect(out).toContain("SUPABASE_ANON_KEY=test-anon-key");
+ expect(out).toContain("SUPABASE_SERVICE_ROLE_KEY=test-service-key");
+ });
+
+ it("ends with a trailing newline", () => {
+ const out = renderEnv({
+ slug: "s",
+ ports,
+ redisDb: 0,
+ jwt,
+ portless: false
+ });
+ expect(out.endsWith("\n")).toBe(true);
+ });
+});
+
+describe("renderEnv (portless enabled)", () => {
+ it("emits portless hostnames for app and supabase", () => {
+ const out = renderEnv({
+ slug: "feat-x",
+ ports,
+ redisDb: 3,
+ jwt,
+ portless: true,
branchPrefix: "feat-x"
});
expect(out).toContain("CARBON_WORKTREE=feat-x");
- expect(out).toContain("ERP_URL=https://erp.feat-x.dev");
- expect(out).toContain("MES_URL=https://mes.feat-x.dev");
- expect(out).toContain("SUPABASE_URL=https://api.feat-x.dev");
+ expect(out).toContain("ERP_URL=https://feat-x.erp.dev");
+ expect(out).toContain("MES_URL=https://feat-x.mes.dev");
+ expect(out).toContain("SUPABASE_URL=https://feat-x.api.dev");
+ expect(out).toContain("PORTLESS_TLD=dev");
});
it("wires every port into env vars", () => {
@@ -37,6 +110,7 @@ describe("renderEnv", () => {
ports,
redisDb: 0,
jwt,
+ portless: true,
branchPrefix: "s"
});
expect(out).toContain("PORT_DB=54000");
@@ -44,6 +118,8 @@ describe("renderEnv", () => {
expect(out).toContain("PORT_STUDIO=54002");
expect(out).toContain("PORT_INBUCKET=54003");
expect(out).toContain("PORT_INNGEST=54004");
+ expect(out).toContain("PORT_ERP=54005");
+ expect(out).toContain("PORT_MES=54006");
});
it("places redis db index in REDIS_URL", () => {
@@ -52,6 +128,7 @@ describe("renderEnv", () => {
ports,
redisDb: 7,
jwt,
+ portless: true,
branchPrefix: "s"
});
expect(out).toMatch(/REDIS_URL=redis:\/\/localhost:\d+\/7/);
@@ -63,6 +140,7 @@ describe("renderEnv", () => {
ports,
redisDb: 0,
jwt,
+ portless: true,
branchPrefix: "s"
});
expect(out).toContain("SUPABASE_JWT_SECRET=test-secret");
@@ -76,6 +154,7 @@ describe("renderEnv", () => {
ports,
redisDb: 0,
jwt,
+ portless: true,
branchPrefix: "s"
});
expect(out.endsWith("\n")).toBe(true);
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index 6d96cc0f7e..ba416222c5 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -8,12 +8,15 @@ export function renderEnv(opts: {
ports: PortMap;
redisDb: number;
jwt: JwtCreds;
- // Sanitized branch segment, e.g. `feat/boo` → `boo`, `main` → `main`.
- // Always non-empty — callers fall back to slug when branch is detached.
- branchPrefix: string;
+ /** When true, write portless hostnames; when false, write http://localhost:PORT URLs. */
+ portless: boolean;
+ /** Required when portless is true. e.g. "dev" for branch "dev". */
+ branchPrefix?: string;
}): string {
- const { slug, ports, redisDb, jwt, branchPrefix } = opts;
+ const { slug, ports, redisDb, jwt, portless, branchPrefix } = opts;
+
const host = (sub: string) => `${sub}.${branchPrefix}.dev`;
+ const local = (port: number) => `http://localhost:${port}`;
const lines: string[] = [];
lines.push("# Generated by crbn. Do not edit by hand.");
@@ -21,22 +24,34 @@ export function renderEnv(opts: {
lines.push("# values here override .env. The user's .env is left untouched.");
lines.push("");
lines.push(`CARBON_WORKTREE=${slug}`);
- lines.push("PORTLESS_TLD=dev");
+ if (portless) lines.push("PORTLESS_TLD=dev");
lines.push("");
lines.push("# Internal compose ports (apps do not read these directly)");
for (const [k, v] of Object.entries(ports)) lines.push(`${k}=${v}`);
lines.push("");
- lines.push("# App-facing URLs (portless hostnames)");
- lines.push(`DOMAIN=${host("erp")}`);
- lines.push(`ERP_URL=https://${host("erp")}`);
- lines.push(`MES_URL=https://${host("mes")}`);
- lines.push(`VERCEL_URL=https://${host("erp")}`);
- lines.push(`GTM_URL=https://${host("starter")}`);
+ lines.push(
+ portless
+ ? "# App-facing URLs (portless hostnames)"
+ : "# App-facing URLs (localhost)"
+ );
+ lines.push(`DOMAIN=${portless ? host("erp") : "localhost"}`);
+ lines.push(
+ `ERP_URL=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`
+ );
+ lines.push(
+ `MES_URL=${portless ? `https://${host("mes")}` : local(ports.PORT_MES)}`
+ );
+ lines.push(
+ `VERCEL_URL=${portless ? `https://${host("erp")}` : local(ports.PORT_ERP)}`
+ );
+ if (portless) lines.push(`GTM_URL=https://${host("starter")}`);
lines.push("");
lines.push(
"# Supabase (per-worktree dev keys, minted from random JWT_SECRET)"
);
- lines.push(`SUPABASE_URL=https://${host("api")}`);
+ lines.push(
+ `SUPABASE_URL=${portless ? `https://${host("api")}` : local(ports.PORT_API)}`
+ );
lines.push(
`SUPABASE_DB_URL=postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`
);
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index d06182c1f6..15a583e5b2 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -40,6 +40,12 @@ const main = defineCommand({
default: false,
description:
"Always docker compose pull (default: skip when all images exist locally)"
+ },
+ borrow: {
+ type: "boolean",
+ default: false,
+ description:
+ "Pick another worktree's running containers to use instead of booting a new stack"
}
},
run: ({ args }) =>
@@ -47,7 +53,8 @@ const main = defineCommand({
migrate: args.migrate !== false,
regen: args.regen !== false,
apps: args.apps !== false,
- pull: args.pull === true
+ pull: args.pull === true,
+ borrow: args.borrow === true
})
}),
down: defineCommand({
diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.ts
index 490ed0927d..bf8f24d98d 100644
--- a/packages/dev/src/prompts.ts
+++ b/packages/dev/src/prompts.ts
@@ -13,11 +13,36 @@ import { join } from "pathe";
import pc from "picocolors";
import { APP_CHOICES, type AppId } from "./constants.js";
import { branchExists, deleteBranch, listWorktrees } from "./git.js";
+import { listSlugs } from "./worktree.js";
// git-check-ref-format(1) rules.
const INVALID_BRANCH_RE =
/(^[/-])|([/-]$)|(\.\.)|(@\{)|([\s~^:?*[\\])|(\/{2,})/;
+export async function pickBorrowSlug(currentSlug: string): Promise<string> {
+ const registry = listSlugs();
+ const others = Object.entries(registry).filter(([s]) => s !== currentSlug);
+ if (others.length === 0) {
+ throw new Error(
+ `No other worktree stacks in ~/.carbon/dev-ports.json.\nRun \`crbn up\` in another worktree first.`
+ );
+ }
+ if (others.length === 1) {
+ log.info(`auto-selecting only available worktree: ${others[0]![0]}`);
+ return others[0]![0];
+ }
+ const picked = await select({
+ message: "Borrow containers from which worktree?",
+ options: others.map(([s, entry]) => ({
+ value: s,
+ label: s,
+ hint: entry.worktreeRoot
+ }))
+ });
+ if (isCancel(picked)) abort();
+ return picked as string;
+}
+
export async function pickApps(): Promise<AppId[]> {
const fromEnv = process.env.CARBON_DEV_APPS;
if (fromEnv) {
diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.ts
index 3a04d588fc..4e011e366c 100644
--- a/packages/dev/src/services/apps.ts
+++ b/packages/dev/src/services/apps.ts
@@ -4,6 +4,7 @@ import { type ExecaChildProcess, execa } from "execa";
import { join } from "pathe";
import pc from "picocolors";
import { isAtLeastAsNew, onShutdown, readLines } from "../helpers.js";
+import type { PortMap } from "../worktree.js";
const APP_COLORS: Record<string, (s: string) => string> = {
erp: pc.cyan,
@@ -38,14 +39,18 @@ function spawnAppEnv(repoRoot: string, appId: string): NodeJS.ProcessEnv {
return env as NodeJS.ProcessEnv;
}
-// Invoke portless directly per app, bypassing the per-app `dev` script.
-// Older branches still have `dev: portless` which recurses into itself in
-// portless default mode, racing to register `<prefix>.<app>.dev`.
+const APP_PORT_KEYS: Partial<Record<string, keyof PortMap>> = {
+ erp: "PORT_ERP",
+ mes: "PORT_MES"
+};
+
export function spawnApps(opts: {
root: string;
apps: string[];
+ ports: PortMap;
+ portless: boolean;
}): Promise<void> {
- const { root, apps } = opts;
+ const { root, apps, ports, portless } = opts;
let shuttingDown = false;
@@ -53,14 +58,30 @@ export function spawnApps(opts: {
const color = APP_COLORS[id] ?? ((s: string) => s);
// detached: own process group so `process.kill(-pid, sig)` reaches the
// whole subtree (portless → react-router → vite → esbuild).
- const child = execa("portless", ["--script", "dev:app", "run", "--force"], {
- cwd: join(root, "apps", id),
- env: spawnAppEnv(root, id),
- preferLocal: true,
- reject: false,
- stdin: "ignore",
- detached: true
- });
+ const child = portless
+ ? execa("portless", ["--script", "dev:app", "run", "--force"], {
+ cwd: join(root, "apps", id),
+ env: spawnAppEnv(root, id),
+ preferLocal: true,
+ reject: false,
+ stdin: "ignore",
+ detached: true
+ })
+ : (() => {
+ const portKey = APP_PORT_KEYS[id];
+ const port = portKey ? ports[portKey] : undefined;
+ return execa("pnpm", ["run", "dev:app"], {
+ cwd: join(root, "apps", id),
+ env: {
+ ...spawnAppEnv(root, id),
+ HOST: "127.0.0.1",
+ ...(port !== undefined ? { PORT: String(port) } : {})
+ },
+ reject: false,
+ stdin: "ignore",
+ detached: true
+ });
+ })();
const prefix = color(pc.bold(`${id.padEnd(3)} | `));
const pipe = (
diff --git a/packages/dev/src/ui.ts b/packages/dev/src/ui.ts
index e4c3166d8f..f69434d548 100644
--- a/packages/dev/src/ui.ts
+++ b/packages/dev/src/ui.ts
@@ -1,6 +1,6 @@
import Table from "cli-table3";
import pc from "picocolors";
-import { type AppId, TLD } from "./constants.js";
+import type { AppId } from "./constants.js";
import type { Container } from "./services/compose.js";
import { PORT_NAMES, type PortMap, SHARED_REDIS_PORT } from "./worktree.js";
@@ -124,19 +124,44 @@ function formatPorts(c: Container): string {
/** Boxed list of URLs + DB DSN for the up-summary. */
export function summaryLines(
ports: PortMap,
- branchPrefix: string,
- apps: readonly AppId[]
+ apps: readonly AppId[],
+ /** When provided, show portless hostnames; otherwise show localhost URLs. */
+ branchPrefix?: string
): string[] {
- const host = (sub: string) => `https://${sub}.${branchPrefix}.${TLD}`;
+ const url = branchPrefix
+ ? (sub: string) => `https://${sub}.${branchPrefix}.${TLD}`;
+ : (sub: string, port: number) => `http://localhost:${port}`;
const dbUrl = `postgresql://postgres:postgres@localhost:${ports.PORT_DB}/postgres`;
const lines: string[] = [];
- if (apps.includes("erp")) lines.push(row(pc.cyan, "ERP", host("erp")));
- if (apps.includes("mes")) lines.push(row(pc.magenta, "MES", host("mes")));
+ if (apps.includes("erp"))
+ lines.push(row(pc.cyan, "ERP", url("erp", ports.PORT_ERP)));
+ if (apps.includes("mes"))
+ lines.push(row(pc.magenta, "MES", url("mes", ports.PORT_MES)));
lines.push(
- row(pc.green, "API", host("api"), ports.PORT_API),
- row(pc.green, "Studio", host("studio"), ports.PORT_STUDIO),
- row(pc.yellow, "Mail", host("mail"), ports.PORT_INBUCKET),
- row(pc.blue, "Inngest", host("inngest"), ports.PORT_INNGEST),
+ row(
+ pc.green,
+ "API",
+ url("api", ports.PORT_API),
+ branchPrefix ? ports.PORT_API : undefined
+ ),
+ row(
+ pc.green,
+ "Studio",
+ url("studio", ports.PORT_STUDIO),
+ branchPrefix ? ports.PORT_STUDIO : undefined
+ ),
+ row(
+ pc.yellow,
+ "Mail",
+ url("mail", ports.PORT_INBUCKET),
+ branchPrefix ? ports.PORT_INBUCKET : undefined
+ ),
+ row(
+ pc.blue,
+ "Inngest",
+ url("inngest", ports.PORT_INNGEST),
+ branchPrefix ? ports.PORT_INNGEST : undefined
+ ),
`${pc.gray(pc.bold("Postgres".padEnd(8)))} ${pc.gray(dbUrl)}`
);
return lines;
diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.ts
index 5f1a890c77..0ad3f99804 100644
--- a/packages/dev/src/worktree.ts
+++ b/packages/dev/src/worktree.ts
@@ -20,7 +20,9 @@ export const PORT_NAMES = [
"PORT_API",
"PORT_STUDIO",
"PORT_INBUCKET",
- "PORT_INNGEST"
+ "PORT_INNGEST",
+ "PORT_ERP",
+ "PORT_MES"
] as const;
type PortName = (typeof PORT_NAMES)[number];
diff --git a/packages/form/src/components/Hidden.tsx b/packages/form/src/components/Hidden.tsx
index abdb5db5e7..ee8c490dd8 100644
--- a/packages/form/src/components/Hidden.tsx
+++ b/packages/form/src/components/Hidden.tsx
@@ -15,16 +15,17 @@ type HiddenProps = InputProps & {
const Hidden = forwardRef<HTMLInputElement, HiddenProps>(
({ name, value, ...rest }, ref) => {
const { getInputProps, error } = useField(name);
+ const { defaultValue, ...inputProps } = getInputProps({
+ id: name,
+ ...rest
+ });
return (
<FormControl isInvalid={!!error}>
<InputBase
ref={ref}
- {...getInputProps({
- id: name,
- ...rest
- })}
- value={value}
+ {...inputProps}
+ {...(value !== undefined ? { value } : { defaultValue })}
type="hidden"
/>
{error && <FormErrorMessage>{error}</FormErrorMessage>}
diff --git a/packages/react/src/hooks/useRealtimeChannel.ts b/packages/react/src/hooks/useRealtimeChannel.ts
index bdfd9eafe6..e834d362ff 100644
--- a/packages/react/src/hooks/useRealtimeChannel.ts
+++ b/packages/react/src/hooks/useRealtimeChannel.ts
@@ -2,6 +2,22 @@ import type { RealtimeChannel, SupabaseClient } from "@supabase/supabase-js";
import { REALTIME_SUBSCRIBE_STATES } from "@supabase/supabase-js";
import { useCallback, useEffect, useRef } from "react";
import { useCarbon } from "../CarbonContext";
+import { toast } from "../Toast";
+
+function formatSubscribeErr(err: unknown): string {
+ if (err == null) return "No error details";
+ if (typeof err === "string") return err.trim() || "No error details";
+ if (err instanceof Error) return err.message || "No error details";
+ if (typeof err === "object") {
+ const o = err as Record<string, unknown>;
+ if (typeof o.message === "string" && o.message.trim()) return o.message;
+ }
+ try {
+ return JSON.stringify(err);
+ } catch {
+ return String(err);
+ }
+}
interface UseRealtimeChannelOptions<TDeps extends any[]> {
topic: string;
@@ -12,14 +28,27 @@ interface UseRealtimeChannelOptions<TDeps extends any[]> {
) => RealtimeChannel;
enabled?: boolean;
dependencies?: TDeps;
+ /** When true, CHANNEL_ERROR / TIMED_OUT open a toast. Defaults to true in dev, false in prod. */
+ notifyOnSubscribeError?: boolean;
}
export const useRealtimeChannel = <TDeps extends any[]>(
options: UseRealtimeChannelOptions<TDeps>
) => {
- const { topic, setup, enabled = true, dependencies = [] } = options;
+ const {
+ topic,
+ setup,
+ enabled = true,
+ dependencies = [],
+ notifyOnSubscribeError = process.env.NODE_ENV === "development"
+ } = options;
const channelRef = useRef<RealtimeChannel | null>(null);
const isTearingDownRef = useRef(false);
+ const lastErrorToastAtRef = useRef<number>(0);
+ const retryCountRef = useRef(0);
+ const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Updated each effect run so the retry timer always calls the latest subscribe closure.
+ const doSubscribeRef = useRef<() => Promise<void>>(() => Promise.resolve());
const { carbon, isRealtimeAuthSet } = useCarbon();
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
@@ -31,21 +60,12 @@ export const useRealtimeChannel = <TDeps extends any[]>(
// Define teardown inline - NOT in dependency array
const teardown = async () => {
- // Re-entrancy guard
- if (isTearingDownRef.current) {
- console.log(
- `🌀 Teardown already in progress for ${topic}, skipping...`
- );
- return;
- }
+ if (isTearingDownRef.current) return;
- console.log(`🌀 Tearing down realtime channel ${topic}...`);
const channel = channelRef.current;
-
if (!channel) return;
isTearingDownRef.current = true;
-
try {
// Add timeout to prevent hanging indefinitely
await Promise.race([
@@ -55,22 +75,24 @@ export const useRealtimeChannel = <TDeps extends any[]>(
)
]);
} catch (error) {
- console.error(`❌ Error removing channel ${topic}:`, error);
+ console.error(`Error removing channel ${topic}:`, error);
} finally {
- console.log(`🌀 Realtime channel ${topic} torn down.`);
channelRef.current = null;
isTearingDownRef.current = false;
}
};
if (!isRealtimeAuthSet || !enabled) {
- // If disabled/auth lost, tear down any existing channel
+ if (retryTimerRef.current) {
+ clearTimeout(retryTimerRef.current);
+ retryTimerRef.current = null;
+ }
+ retryCountRef.current = 0;
void teardown();
return;
}
- // Always create a fresh channel instance when deps change
- (async () => {
+ const doSubscribe = async () => {
// Ensure previous instance is gone before creating a new one
if (channelRef.current) {
await teardown();
@@ -78,27 +100,44 @@ export const useRealtimeChannel = <TDeps extends any[]>(
try {
const channel = carbon.channel(topic);
-
const configuredChannel = memoSetup(
channel,
carbon,
dependencies as TDeps
);
-
channelRef.current = configuredChannel;
configuredChannel.subscribe(async (status, err) => {
- console.log(`🌀 Realtime channel ${topic} status:`, status);
if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
+ retryCountRef.current = 0;
return;
}
- // Treat error/timeout/closed as dead; tear down so effect can recreate
- if (
+ const isRetriableError =
status === REALTIME_SUBSCRIBE_STATES.CHANNEL_ERROR ||
- status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT ||
- status === REALTIME_SUBSCRIBE_STATES.CLOSED
- ) {
+ status === REALTIME_SUBSCRIBE_STATES.TIMED_OUT;
+
+ if (isRetriableError && notifyOnSubscribeError) {
+ const now = Date.now();
+ if (now - lastErrorToastAtRef.current > 12_000) {
+ lastErrorToastAtRef.current = now;
+ toast.error(`Realtime disconnected (${topic})`, {
+ description: `${status}: ${formatSubscribeErr(err)}`,
+ duration: 10_000
+ });
+ }
+ }
+
+ if (isRetriableError) {
+ await teardown();
+ // Exponential backoff: 5s, 10s, 20s, 40s, 60s max
+ const delay = Math.min(5_000 * 2 ** retryCountRef.current, 60_000);
+ retryCountRef.current++;
+ retryTimerRef.current = setTimeout(() => {
+ retryTimerRef.current = null;
+ void doSubscribeRef.current();
+ }, delay);
+ } else if (status === REALTIME_SUBSCRIBE_STATES.CLOSED) {
await teardown();
}
});
@@ -107,11 +146,26 @@ export const useRealtimeChannel = <TDeps extends any[]>(
`Failed to subscribe to realtime channel ${topic}:`,
error
);
+ if (notifyOnSubscribeError) {
+ toast.error(`Realtime setup failed (${topic})`, {
+ description:
+ error instanceof Error ? error.message : formatSubscribeErr(error)
+ });
+ }
}
- })();
+ };
+
+ // Keep ref up-to-date so retry timers always call the latest closure.
+ doSubscribeRef.current = doSubscribe;
+ void doSubscribe();
// Cleanup on unmount or dependency change
return () => {
+ if (retryTimerRef.current) {
+ clearTimeout(retryTimerRef.current);
+ retryTimerRef.current = null;
+ }
+ retryCountRef.current = 0;
void teardown();
};
}, [
@@ -119,8 +173,9 @@ export const useRealtimeChannel = <TDeps extends any[]>(
isRealtimeAuthSet,
enabled,
topic,
- memoSetup
- // teardown is NOT in dependencies - it's defined inline
+ memoSetup,
+ notifyOnSubscribeError
+ // teardown/doSubscribe are NOT in dependencies - defined inline
]);
return channelRef;