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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
crbn: hibernate an idle stack and its dev servers, prune --tree, responsive list (#1848)
Sid9ef4b9065df3
diff --git a/.claude/rules/realtime-system.md b/.claude/rules/realtime-system.mdindex b2102606f7..f3855d1f26 100644--- a/.claude/rules/realtime-system.md+++ b/.claude/rules/realtime-system.md@@ -125,15 +125,34 @@ other down. Every listener registers in a module-level registry andquery cache under `["live", companyId, <name>]`; the hooks keep their`[rows, setRows]` shape. `LiveLists` (in `RealtimeDataProvider`) loads them:-1. IndexedDB first (`<name>:<companyId>`), so pickers have options at once.+1. IndexedDB first (`<name>:<companyId>:<userId>`), so pickers have options at once.2. One `table_changes_since(cursor)` call.3. Only the rows it names are re-read; a named row that does not come back isremoved. The whole list is fetched once per device, and again only when thelog answers `reset` or names more than 500 rows. Ids are re-read 100 perrequest: `.in()` goes in the URL, and a few hundred ids exceed the gateway'slimit.-4. While the tab is open, broadcasts patch the list row by row. After a- reconnect, step 2 runs again.+4. While the tab is open, broadcasts patch the list row by row, in memory+ only. After a reconnect, step 2 runs again.++The stored copy is written only in step 3. A broadcast's patch does not move the+cursor, so the next load re-reads those rows whatever was stored, and storing+means writing the whole list (about 150 ms of blocked page for 150,000 items).++**Who may keep a stored list.** It is company data on a device, so it goes when+the user's access does: `LiveLists` takes `companyIds` (the companies the user+is an employee of, from the shell) and at page load removes every stored list+of another company or another user (`staleStoredKeys`); when+`table_changes_since` refuses the caller (`42501`, removed while the page was+open) the current company's lists are emptied in memory and on the device; and+each app's login page clears the store, whichever way the session ended. A+stored list also expires: its write time is kept beside it+(`<key>:at`, so checking it does not read the list) and a list not written for+24 hours is removed (`STORED_LIST_MAX_AGE_MS`). The check runs at page load+and every hour while a page is open (`BACKGROUND_CHECK_MS`); a visible page+also asks the log again then, which rewrites its own lists (so a list in use+does not expire) and catches a user who has left the company. A browser that never opens+Carbon again keeps its copy: nothing can reach it.### The change logdiff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex 350c719d78..c9759a14c4 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -10,7 +10,8 @@ import {LOADER,useTableChanges} from "@carbon/query";-import { useUser } from "~/hooks";+import { useMemo } from "react";+import { useRouteData, useUser } from "~/hooks";import { customersList } from "~/stores/customers";import { itemsList } from "~/stores/items";import { peopleList } from "~/stores/people";@@ -28,6 +29,20 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {id: userId,company: { id: companyId }} = useUser();+ const shell = useRouteData<{+ companies: { companyId: string | null; role: string | null }[];+ }>(path.to.authenticatedRoot);+ // The companies this user works in. Lists stored for any other are removed+ // from the device when the page loads (see `LiveLists`).+ const companyIds = useMemo(+ () =>+ (shell?.companies ?? []).flatMap((company) =>+ company.role === "employee" && company.companyId+ ? [company.companyId]+ : []+ ),+ [shell?.companies]+ );// Quantities are maintained incrementally by triggers on itemLedger, so this// fires on the posting itself. Invalidate rather than refetch: the on-hand map@@ -50,6 +65,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {<LiveListscompanyId={companyId}userId={userId}+ companyIds={companyIds}lists={LISTS}storage={storage}/>diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.tsindex d58e6940b5..fa4c433c4a 100644--- a/apps/erp/app/modules/shared/shared.server.ts+++ b/apps/erp/app/modules/shared/shared.server.ts@@ -19,7 +19,7 @@ import { startOfWeek } from "@internationalized/date";import { renderAsync } from "@react-email/components";import type { SupabaseClient } from "@supabase/supabase-js";import type { LoaderFunctionArgs } from "react-router";-import { createCookieSessionStorage } from "react-router";+import { createCookieSessionStorage, data } from "react-router";import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";import {getCustomerContact,@@ -876,3 +876,19 @@ export async function clearOnboardingDraft(request: Request): Promise<string> {session.set(ONBOARDING_DRAFT_KEY, undefined);return onboardingDraftStorage.commitSession(session);}++// For a list that is the same for every company and changes only with a deploy+// or the database's own reference data. `private`: the route still needs a+// session, so no shared cache may hold it.+export const DAY_CACHE_HEADERS = { "Cache-Control": "private, max-age=86400" };++/**+ * A global `{ data, error }` list the browser keeps for a day, across page+ * loads. An empty or failed read is not kept: it would stick for the day.+ */+export function keptForADay<T extends { data: unknown[] | null }>(result: T) {+ return data(+ result,+ result.data?.length ? { headers: DAY_CACHE_HEADERS } : undefined+ );+}diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsxindex e93e91d4e2..c9fb1c7c3f 100644--- a/apps/erp/app/routes/_public+/login.tsx+++ b/apps/erp/app/routes/_public+/login.tsx@@ -40,6 +40,7 @@ import { sendVerificationCode } from "@carbon/auth/verification.server";import { isSsoEnabled, isSsoRequiredForEmail } from "@carbon/ee/sso.server";import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";import { AccountLockout, Ratelimit, redis } from "@carbon/kv";+import { getLogger } from "@carbon/logger";import {Alert,AlertDescription,@@ -291,6 +292,16 @@ export async function action({ request }: ActionFunctionArgs) {}export default function LoginRoute() {+ // A signed-out user lands here however the session ended (sign out, expiry,+ // a revoked account), so this is where the lists kept on the device go.+ useEffect(() => {+ import("localforage")+ .then((storage) => storage.default.clear())+ .catch((error) =>+ getLogger("erp", "login").warn("stored lists not cleared", { error })+ );+ }, []);+const { t } = useLingui();const {hasOutlookAuth,diff --git a/apps/erp/app/routes/api+/countries.ts b/apps/erp/app/routes/api+/countries.tsindex f2cb6a33f4..52769940b4 100644--- a/apps/erp/app/routes/api+/countries.ts+++ b/apps/erp/app/routes/api+/countries.ts@@ -7,9 +7,11 @@ import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";import type { LoaderFunctionArgs } from "react-router";import { getCountries } from "~/modules/shared";+import { keptForADay } from "~/modules/shared/shared.server";+export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});- return await getCountries(client);+ return keptForADay(await getCountries(client));}export const clientLoader = cachedClientLoader<typeof loader>({diff --git a/apps/erp/app/routes/api+/docs.ts b/apps/erp/app/routes/api+/docs.tsindex 71244ac7d1..ea12550bab 100644--- a/apps/erp/app/routes/api+/docs.ts+++ b/apps/erp/app/routes/api+/docs.ts@@ -8,6 +8,8 @@ import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";import { getClientIp } from "@carbon/utils";import { data, type LoaderFunctionArgs } from "react-router";+import { DAY_CACHE_HEADERS } from "~/modules/shared/shared.server";+export async function loader({ request }: LoaderFunctionArgs) {const ip = getClientIp(request) ?? "127.0.0.1";const ratelimit = new Ratelimit({@@ -21,7 +23,8 @@ export async function loader({ request }: LoaderFunctionArgs) {throw data({ error: "Rate limit exceeded" }, { status: 429 });}- return swaggerDocsSchema;+ // Fixed until the next deploy, and the limit above is 20 an hour.+ return data(swaggerDocsSchema, { headers: DAY_CACHE_HEADERS });}export const clientLoader = cachedClientLoader<typeof loader>({diff --git a/apps/erp/app/routes/api+/timezones.ts b/apps/erp/app/routes/api+/timezones.tsindex 660bc892dd..1f1adb68f7 100644--- a/apps/erp/app/routes/api+/timezones.ts+++ b/apps/erp/app/routes/api+/timezones.ts@@ -5,18 +5,15 @@import { requirePermissions } from "@carbon/auth/auth.server";import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";import type { LoaderFunctionArgs } from "react-router";-import { data } from "react-router";-import { getCachedTimezoneNames } from "~/modules/shared/shared.server";+import {+ getCachedTimezoneNames,+ keptForADay+} from "~/modules/shared/shared.server";export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});- const result = await getCachedTimezoneNames(client);- if (!result.data?.length) return data(result);- // The same list for every company, and it only changes with the database's- // tzdata: the browser keeps it across page loads as long as the server does.- return data(result, {- headers: { "Cache-Control": "private, max-age=86400" }- });+ // Only changes with the database's tzdata.+ return keptForADay(await getCachedTimezoneNames(client));}export const clientLoader = cachedClientLoader<typeof loader>({diff --git a/apps/erp/app/routes/api+/webhook.tables.ts b/apps/erp/app/routes/api+/webhook.tables.tsindex 792b23f5bb..21b8cc4094 100644--- a/apps/erp/app/routes/api+/webhook.tables.ts+++ b/apps/erp/app/routes/api+/webhook.tables.ts@@ -7,10 +7,12 @@ import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";import type { LoaderFunctionArgs } from "react-router";import { getWebhookTables } from "~/modules/settings/settings.service";+import { keptForADay } from "~/modules/shared/shared.server";+export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});- return await getWebhookTables(client);+ return keptForADay(await getWebhookTables(client));}export const clientLoader = cachedClientLoader<typeof loader>({diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 1fc5ba464b..51768e28cf 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -17,6 +17,9 @@ const file = "/file"; // from ~/routes/file+ folderconst share = "/share"; // from ~/routes/shared+ folderconst onboarding = "/onboarding"; // from ~/routes/onboarding+ folderconst selectCompany = "/select-company"; // from ~/routes/select-company+ folder+// Set per build in vite.config.ts (absent under vitest). On a URL whose response+// the browser keeps for a day (`keptForADay`), it makes each deploy ask again.+const build = `v=${import.meta.env?.VITE_BUILD_ID ?? "dev"}`;export const MES_URL = getMESUrl();export const ERP_URL = getAppUrl();@@ -114,7 +117,7 @@ export const path = {),chat: `${api}/ai/chat`,costCenters: `${api}/accounting/cost-centers`,- countries: `${api}/countries`,+ countries: `${api}/countries?${build}`,createCsvLookup: `${api}/csv/create-lookup`,currencies: `${api}/accounting/currencies`,customerContacts: (id: string) =>@@ -130,7 +133,7 @@ export const path = {generatePath(`${api}/sales/digital-quote/${id}`),digitalSupplierQuote: (id: string) =>generatePath(`${api}/purchasing/digital-quote/${id}`),- docs: `${api}/docs`,+ docs: `${api}/docs?${build}`,employeeTypes: `${api}/users/employee-types`,emptyPermissions: `${api}/users/empty-permissions`,failureModes: `${api}/resources/failure-modes`,@@ -335,7 +338,7 @@ export const path = {tags: (table?: string) =>generatePath(`${api}/shared/tags?table=${table}`),timecard: `${api}/people/timecard`,- timezones: `${api}/timezones`,+ timezones: `${api}/timezones?${build}`,unitOfMeasures: `${api}/items/uoms`,userSelectGroupEmails: (groupId: string) =>generatePath(`${api}/users/select/groups/${groupId}/emails`),@@ -356,7 +359,7 @@ export const path = {`${api}/users/select/search?q=${encodeURIComponent(q)}&type=${type ?? ""}`),webhookStripe: `${api}/webhook/stripe`,- webhookTables: `${api}/webhook/tables`,+ webhookTables: `${api}/webhook/tables?${build}`,workCenters: `${api}/resources/work-centers`,workCentersByLocation: (id: string) =>generatePath(`${api}/resources/work-centers?location=${id}`)diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.tsindex ea5d429681..df66fd6639 100644--- a/apps/erp/vite.config.ts+++ b/apps/erp/vite.config.ts@@ -6,6 +6,7 @@ import {applyDotenvToProcessEnv,clientOnlyAlias,linguiWithoutIdQuery,+ stackActivity,} from "@carbon/dev/vite";import { getConfig } from "@lingui/conf";import { lingui } from "@lingui/vite-plugin";@@ -18,6 +19,16 @@ import { defineConfig, PluginOption } from "vite";export default defineConfig(({ command, isSsrBuild, mode }) => {applyDotenvToProcessEnv(mode, import.meta.dirname);+ // One id per build, the same in the client and server bundles. `path.to.api`+ // puts it on the reference lists the browser keeps for a day, so a deploy+ // is never served the copy cached under the previous one. The deployment on+ // Vercel (a redeploy of one commit can still change what those lists hold);+ // elsewhere the build's own start time, which also changes per build.+ process.env.VITE_BUILD_ID ??=+ process.env.VERCEL_DEPLOYMENT_ID?.replace(/^dpl_/, "").slice(0, 12) ??+ process.env.VERCEL_GIT_COMMIT_SHA?.slice(0, 12) ??+ Date.now().toString(36);+/*** SSR dependencies that must be bundled into the server output rather than* left as bare `import`s. Defined once and applied to BOTH `ssr.noExternal`@@ -129,6 +140,7 @@ export default defineConfig(({ command, isSsrBuild, mode }) => {],},plugins: [+ stackActivity(),tailwindcss(),linguiWithoutIdQuery(lingui({ macroTransform: true })),reactRouter(),diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsxindex e5242c642e..4a717c9808 100644--- a/apps/mes/app/components/RealtimeDataProvider.tsx+++ b/apps/mes/app/components/RealtimeDataProvider.tsx@@ -5,9 +5,12 @@"use client";import { LiveLists } from "@carbon/query";+import { useRouteData } from "@carbon/react";+import { useMemo } from "react";import { useUser } from "~/hooks";import { itemsList } from "~/stores/items";import { peopleList } from "~/stores/people";+import { path } from "~/utils/path";// Module-level so their identity is stable across renders.const LISTS = [itemsList, peopleList];@@ -18,12 +21,27 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {id: userId,company: { id: companyId }} = useUser();+ const shell = useRouteData<{+ companies: { companyId: string | null; role: string | null }[];+ }>(path.to.authenticatedRoot);+ // The companies this user works in. Lists stored for any other are removed+ // from the device when the page loads (see `LiveLists`).+ const companyIds = useMemo(+ () =>+ (shell?.companies ?? []).flatMap((company) =>+ company.role === "employee" && company.companyId+ ? [company.companyId]+ : []+ ),+ [shell?.companies]+ );return (<><LiveListscompanyId={companyId}userId={userId}+ companyIds={companyIds}lists={LISTS}storage={storage}/>diff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsxindex 25ef90ebd8..d3eadeaa47 100644--- a/apps/mes/app/routes/_public+/login.tsx+++ b/apps/mes/app/routes/_public+/login.tsx@@ -34,6 +34,7 @@ import { getUserByEmail } from "@carbon/auth/users.server";import { isSsoEnabled, isSsoRequiredForEmail } from "@carbon/ee/sso.server";import { Hidden, Input, Submit, ValidatedForm, validator } from "@carbon/form";import { AccountLockout, Ratelimit, redis } from "@carbon/kv";+import { getLogger } from "@carbon/logger";import {Alert,AlertDescription,@@ -53,7 +54,7 @@ import {browserSupportsWebAuthn,startAuthentication} from "@simplewebauthn/browser";-import { useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import { LuCircleAlert, LuFingerprint } from "react-icons/lu";import type {ActionFunctionArgs,@@ -238,6 +239,16 @@ export async function action({ request }: ActionFunctionArgs) {}export default function LoginRoute() {+ // A signed-out user lands here however the session ended (sign out, expiry,+ // a revoked account), so this is where the lists kept on the device go.+ useEffect(() => {+ import("localforage")+ .then((storage) => storage.default.clear())+ .catch((error) =>+ getLogger("mes", "login").warn("stored lists not cleared", { error })+ );+ }, []);+const { t } = useLingui();const {hasOutlookAuth,diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.tsindex a1c6437879..8c8dbebfe6 100644--- a/apps/mes/vite.config.ts+++ b/apps/mes/vite.config.ts@@ -6,6 +6,7 @@ import {applyDotenvToProcessEnv,clientOnlyAlias,linguiWithoutIdQuery,+ stackActivity,} from "@carbon/dev/vite";import { reactRouter } from "@react-router/dev/vite";import { getConfig } from "@lingui/conf";@@ -107,6 +108,7 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {allowedHosts: [".ngrok-free.app", ".w.modal.host", ".w.modal.dev", ".dev", ".localhost", "host.docker.internal"],},plugins: [+ stackActivity(),tailwindcss(),linguiWithoutIdQuery(lingui({ macroTransform: true })),reactRouter(),diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.mdindex 109be0f43d..a79dc91de5 100644--- a/packages/dev/AGENTS.md+++ b/packages/dev/AGENTS.md@@ -31,7 +31,7 @@ pnpm --filter @carbon/dev smoke # real containers: slots, fresh migrate, u## Key Patterns-- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `prune` (destroys stacks whose worktree directory is gone or that have no slot — the cleanup for worktrees deleted without `crbn remove`; `--all` destroys every stack on the machine and keeps worktrees and live slots), `list`, `status`, `reset`, `migrate`, `restore`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)+- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `prune` (destroys stacks whose worktree directory is gone or that have no slot — the cleanup for worktrees deleted without `crbn remove`; `--all` destroys every stack on the machine and keeps worktrees and live slots; `--tree` also runs `git worktree prune`, and with `--all` removes this repo's linked worktrees — never the main checkout, the current one, or one with uncommitted changes or a detached HEAD; branches are kept), `list`, `status`, `reset`, `migrate`, `restore`, `copy` (env sync), `reload` (`crbn reload <service...>` → `docker compose up -d --force-recreate` a subset, applying compose/`.env.local` edits without restarting the app dev servers)- **Restore** (`commands/restore.ts`): `crbn restore <file>` wraps `scripts/restore-database.sh` (the SQL is deliberately NOT ported) and adds worktree/`PORT_DB` resolution, a confirmation gate, and the trailing `applyMigrations` + `db:types`. The script truncates the local `supabase_migrations` ledger before restoring so the dump's own ledger lands — the ledger must travel WITH the schema, else the dump's older schema pairs with the local newer ledger and the trailing migrate step silently no-ops (leaving weeks of migrations missing while the ledger claims them applied). It deliberately does NOT boot a partial stack the way `crbn migrate` does — a restore rewrites `auth`/`storage`, whose schemas GoTrue and Storage build via their own migrations, so it requires a fully booted stack (`serviceSchemasReady` probes for GoTrue's `auth.users.email_confirmed_at`, `storage.objects`/`storage.buckets` AND Realtime's `realtime.messages` — the restore script's `to_regclass` guards mean a missing Storage schema would otherwise let the restore finish with no buckets seeded) and refuses otherwise — the backup carries the SOURCE schema, which is usually behind the branch. **`--scrub-emails` defaults ON here, inverting the script's opt-in default**, so a restore cannot drop real customer addresses into a local DB unless asked. By default the script truncates `storage.objects` (kept rows would point at files that live only in the source environment's backend, so downloads 404); pass `--keep-storage-objects` to retain them and the dump's buckets when you need realistic storage metadata, e.g. profiling storage RLS.- **Stack boot** (`commands/up.ts`): Docker Compose → wait Postgres → wait service schemas → migrations → regen types → spawn apps → portless aliases- **Migrations need three services, not just Postgres**: they write into `storage.buckets`, GoTrue's `auth` columns and `realtime.messages`, which Storage, GoTrue and Realtime build on first boot. `waitForServiceSchemas` gates every migrate on a fresh volume; standalone `crbn migrate` boots `postgres` + `gotrue` + `storage` + `realtime` for the same reason. A from-zero migrate takes about 5 s once they are up, so there is nothing to gain from caching a migrated volume.@@ -49,6 +49,11 @@ pnpm --filter @carbon/dev smoke # real containers: slots, fresh migrate, u- **`restart: on-failure`** on every compose service: a crash restarts the container, a Docker daemon start does not. A stack only comes up through `crbn up`.- **The slot registry is locked** (`lockRegistry` in `worktree.ts`): every change to `~/.carbon/dev-ports.json` is read → decide → write under a `mkdir` lock, written through a temp file + rename. Conductor boots workspaces concurrently; without the lock eight simultaneous `crbn up` left one slot in the file. Any new writer must take the lock.- **Compose reads throw** (`composeRead` in `services/compose.ts`): `listContainers` and `listComposeServices` raise compose's own error instead of returning an empty list, which used to pass for "no stack".+- **Hibernation** (`services/hibernate.ts` + `stackActivity()` in `vite.js`), two stages while `crbn up` runs ERP/MES:+ - **Stack** — the dev servers touch `~/.carbon/stacks/<slug>/activity` on each request (`/api/inngest` excluded: Inngest polls it every 5 s). After `CRBN_IDLE_MINUTES` (default 30) without one, `crbn up` writes an `asleep` marker holding its pid and runs `docker compose stop`. The next request is held by the plugin while `crbn up` runs `bootStack` and waits for Postgres and the API — about 8 s.+ - **Dev servers** — they hold more than the containers (roughly 1 GB each). After `CRBN_APPS_IDLE_MINUTES` (default 120) `crbn up` aborts them (`spawnApps`' `signal`) and listens on their ports itself (`startWaker`). A request there cannot be handed over — the dev server needs that port — so a browser gets a page that polls and reloads, anything else a 503 with `x-crbn-waking`. Inngest polls and WebSocket upgrades (an open tab's Vite client probing for its server) do not wake it. That wake is about 40 s: the dev servers boot from cold.+ - Off for `--no-apps`, `--run`, `--borrow` (the owning `crbn up` does it) and `--no-hibernate`. Traffic that never reaches ERP/MES (`psql`, scripts on the API) does not count; `crbn migrate` and `crbn restore` wake a sleeping stack themselves (`wakeIfAsleep`). `crbn list` and `crbn status` show a hibernated stack.+- **`crbn prune` also clears stale portless routes** (`findStaleAliases`): static aliases crbn registered whose port no live slot owns. `portless prune` only reaps routes that have a process.- **Env**: `env.ts` — `renderEnv()`, `writeEnv()`, `syncAppPortlessConfigs()`- **`--run` flag**: scopes stack lifetime to a command (for headless/CI builds); `--volumes` cleans up Docker volumes on teardowndiff --git a/packages/dev/README.md b/packages/dev/README.mdindex 327c043711..6b6241873c 100644--- a/packages/dev/README.md+++ b/packages/dev/README.md@@ -26,6 +26,7 @@ source ./setup.sh # adds crbn to PATH + installs shell wrapper| `crbn remove --prune` | Also delete the git branch after removing each worktree. || `crbn prune` | Destroy stacks no worktree can reach: slots whose directory is gone, and stacks with no slot. Lists them and confirms first; volumes are wiped. || `crbn prune --all` | Destroy every crbn stack on the machine, running ones included. Worktrees, branches and live slots are kept; the next `crbn up` rebuilds the database. |+| `crbn prune --tree` | Also clean up git worktrees: forget ones whose directory is gone. With `--all`, remove this repo's linked worktrees too. The main checkout, the current worktree, and any with uncommitted changes or a detached HEAD are kept; branches are never deleted. |### Stack@@ -37,6 +38,7 @@ source ./setup.sh # adds crbn to PATH + installs shell wrapper| `crbn up --borrow` | Reuse another worktree's running containers (DB, API, etc). || `crbn up --no-apps` | Services only (postgres, kong, supabase, inngest, mail). || `crbn up --full` | Also start Studio, Postgres-Meta, the edge runtime and imgproxy (HEIC conversion). They are off by default; `crbn reload studio` or `crbn reload imgproxy` starts one on a running stack. |+| `crbn up --no-hibernate` | Keep everything up. By default the containers stop after 30 min without ERP/MES traffic (the next request wakes them in about 8 s), and the dev servers stop after 2 h (that wake takes about 40 s). `CRBN_IDLE_MINUTES` and `CRBN_APPS_IDLE_MINUTES` change the waits. || `crbn up --no-migrate` | Skip database migrations. || `crbn up --no-regen` | Skip type/swagger regeneration. || `crbn up --pull` | Force `docker compose pull` even if images exist locally. |diff --git a/packages/dev/bin/crbn b/packages/dev/bin/crbnindex 25693acf52..e5e3d93eea 100755--- a/packages/dev/bin/crbn+++ b/packages/dev/bin/crbn@@ -440,6 +440,7 @@ crbn — Carbon dev CLI--prune also deletes the git branch.crbn prune Destroy stacks whose worktree is gone.crbn prune --all Destroy every stack on this machine (worktrees kept).+ crbn prune --tree Also forget missing worktrees; with --all, remove clean ones.Stack:crbn up Boot compose stack + apps.@@ -448,6 +449,7 @@ crbn — Carbon dev CLIcrbn up --borrow Reuse another worktree's containers.crbn up --no-apps Services only, no dev servers.crbn up --full Also start Studio, Postgres-Meta, edge runtime, imgproxy.+ crbn up --no-hibernate Don't stop the containers when ERP/MES go quiet.crbn down Stop stack (volumes preserved).crbn down --purge Stop stack, wipe volumes, release the slot.crbn reset Wipe volumes + redis, then up.diff --git a/packages/dev/src/commands/list.ts b/packages/dev/src/commands/list.tsindex 822d359b27..3f37b89af7 100644--- a/packages/dev/src/commands/list.ts+++ b/packages/dev/src/commands/list.ts@@ -6,6 +6,7 @@ import { intro, log, outro } from "@clack/prompts";import pc from "picocolors";import { listWorktrees as gitListWorktrees } from "../git.js";import { dockerProjectStates } from "../services/compose.js";+import { isAsleep } from "../services/hibernate.js";import { worktreesTable } from "../ui.js";import { listSlugs, projectName, slugForWorktreePath } from "../worktree.js";@@ -21,9 +22,11 @@ export async function listWorktrees(opts: { json?: boolean } = {}) {const rows = wts.map((w) => {const slug = slugForWorktreePath(w.path, registry);- const dockerState = slug- ? (dockerStates.get(projectName(slug)) ?? null)- : null;+ const dockerState = !slug+ ? null+ : isAsleep(slug)+ ? "hibernated"+ : (dockerStates.get(projectName(slug)) ?? null);return {path: w.path,branch: w.branch,diff --git a/packages/dev/src/commands/migrate.ts b/packages/dev/src/commands/migrate.tsindex 397e867250..1ec9bce1b9 100644--- a/packages/dev/src/commands/migrate.ts+++ b/packages/dev/src/commands/migrate.ts@@ -15,6 +15,7 @@ import {ensureDockerRunning,stopStack} from "../services/compose.js";+import { wakeIfAsleep } from "../services/hibernate.js";import {applyMigrations,ensureConfigRow,@@ -61,6 +62,8 @@ export async function migrate(opts: { regen?: boolean } = {}) {// .env.local missing or PORT_DB not set — will need to provision.}+ if (await wakeIfAsleep(slug)) log.info("woke the hibernated stack");+// If postgres is already reachable, migrate against the running DB.if (portDb && (await tryConnect("127.0.0.1", portDb, 500))) {return migrateAgainstRunningDb(root, portDb, shouldRegen);diff --git a/packages/dev/src/commands/prune.ts b/packages/dev/src/commands/prune.tsindex 8e05b96202..6076745e40 100644--- a/packages/dev/src/commands/prune.ts+++ b/packages/dev/src/commands/prune.ts@@ -5,15 +5,35 @@import { existsSync } from "node:fs";import { cancel, intro, log, outro } from "@clack/prompts";import pc from "picocolors";+import {+ listWorktrees as gitListWorktrees,+ isDirty,+ mainCheckoutRoot,+ pruneWorktreeEntries,+ removeCleanWorktree,+ type Worktree+} from "../git.js";import { confirmPrune } from "../prompts.js";+import { killOrphanedApps } from "../services/apps.js";import {destroyProject,ensureDockerRunning,flushDb,listCarbonStacks} from "../services/compose.js";-import { pruneStaleRoutes } from "../services/portless.js";-import { listSlugs, projectName, removeSlot } from "../worktree.js";+import {+ findStaleAliases,+ pruneStaleRoutes,+ removeAliases+} from "../services/portless.js";+import {+ getWorktreeRoot,+ listSlugs,+ projectName,+ removeSlot,+ sameWorktreePath,+ slugForWorktreePath+} from "../worktree.js";type Slots = Record<string, { worktreeRoot: string }>;@@ -44,20 +64,69 @@ export function planPrune(return { deadSlugs, projects: [...projects].sort() };}-export async function prune(opts: { all?: boolean } = {}) {+export async function prune(opts: { all?: boolean; tree?: boolean } = {}) {intro(opts.all ? "Carbon · prune --all" : "Carbon · prune");await ensureDockerRunning();+ // --tree: git's side of the same cleanup. Always forget worktrees whose+ // directory is gone; with --all, also remove the linked worktrees of this+ // repo. Never the main checkout or the one we are in, and never one with+ // uncommitted changes or a detached HEAD — `crbn remove` discards those.+ let trees: Worktree[] = [];+ let dirtyTrees: Worktree[] = [];+ if (opts.tree) {+ if (opts.all) {+ const mainRoot = await mainCheckoutRoot();+ const here = await getWorktreeRoot();+ const linked = (await gitListWorktrees()).filter(+ (w) =>+ !w.bare &&+ !sameWorktreePath(w.path, here) &&+ !sameWorktreePath(w.path, mainRoot)+ );+ // A detached worktree's commits are on no branch; removing it would+ // leave them unreachable, so it counts as unsaved work.+ const unsaved = await Promise.all(+ linked.map(async (w) => !w.branch || (await isDirty(w.path)))+ );+ trees = linked.filter((_, i) => !unsaved[i]);+ dirtyTrees = linked.filter((_, i) => unsaved[i]);+ }+ }+ // Runs with the rest of the cleanup, never before the confirmation.+ const forgetMissingTrees = async () => {+ if (opts.tree) await pruneWorktreeEntries();+ };+const slots = listSlugs();const { deadSlugs, projects } = planPrune(slots, await listCarbonStacks(), {all: opts.all});- if (projects.length === 0) {- outro("nothing to prune");+ // Routes whose port no surviving slot owns. `gone` adds the slots of+ // worktrees this run actually removed — not the ones it only meant to.+ const dead = new Set(deadSlugs);+ const staleRoutes = (gone = new Set<string>()) =>+ findStaleAliases(+ new Set(+ Object.entries(slots)+ .filter(([slug]) => !dead.has(slug) && !gone.has(slug))+ .flatMap(([, slot]) => Object.values(slot.ports))+ )+ );+ const routes = staleRoutes();++ if (projects.length === 0 && trees.length === 0) {+ await forgetMissingTrees();+ if (routes.length === 0) {+ outro("nothing to prune");+ return;+ }+ // Routes are not data: the next `crbn up` registers its own again.+ await removeAliases(routes);+ outro(`removed ${routes.length} stale portless route(s)`);return;}- const dead = new Set(deadSlugs);const reasons = new Map(Object.keys(slots).map((slug) => [projectName(slug),@@ -66,13 +135,26 @@ export async function prune(opts: { all?: boolean } = {}) {: slots[slug]!.worktreeRoot]));- log.warn(- projects- .map((p) => `${pc.bold(p)} ${pc.dim(reasons.get(p) ?? "no slot")}`)- .join("\n")- );+ if (projects.length > 0) {+ log.warn(+ projects+ .map((p) => `${pc.bold(p)} ${pc.dim(reasons.get(p) ?? "no slot")}`)+ .join("\n")+ );+ }- if (!(await confirmPrune(projects.length))) {+ if (trees.length > 0) {+ log.warn(+ `worktrees to remove (branches are kept):\n${trees.map((w) => `${pc.bold(w.branch ?? "(detached)")} ${pc.dim(w.path)}`).join("\n")}`+ );+ }+ if (dirtyTrees.length > 0) {+ log.info(+ `kept (uncommitted changes or detached HEAD):\n${dirtyTrees.map((w) => `${w.branch ?? "(detached)"} ${pc.dim(w.path)}`).join("\n")}`+ );+ }++ if (!(await confirmPrune(projects.length, trees.length))) {cancel("prune aborted");process.exit(0);}@@ -83,9 +165,34 @@ export async function prune(opts: { all?: boolean } = {}) {await flushDb(slots[slug]!.redisDb);if (dead.has(slug)) removeSlot(slug);}+ await forgetMissingTrees();+ let removedTrees = 0;+ const removedSlugs = new Set<string>();+ for (const tree of trees) {+ // Checked again, and removed only by git itself: a file saved while the+ // prompt was open makes the tree dirty, and it must then be kept.+ if (await isDirty(tree.path)) {+ log.info(`kept ${tree.path}: it changed while confirming`);+ continue;+ }+ if (!(await removeCleanWorktree(tree.path))) {+ log.info(`kept ${tree.path}: git would not remove it`);+ continue;+ }+ removedTrees++;+ // Only once the tree is really gone: a kept worktree keeps its dev+ // servers, its slot and its routes.+ const slug = slugForWorktreePath(tree.path, slots);+ if (!slug) continue;+ await killOrphanedApps(slots[slug]!.ports);+ removeSlot(slug);+ removedSlugs.add(slug);+ }await pruneStaleRoutes();+ const cleared = staleRoutes(removedSlugs);+ await removeAliases(cleared);outro(- `removed ${projects.length} stack(s), released ${deadSlugs.length} slot(s)`+ `removed ${projects.length} stack(s) and ${removedTrees} worktree(s), released ${deadSlugs.length} slot(s), cleared ${cleared.length} stale portless route(s)`);}diff --git a/packages/dev/src/commands/restore.ts b/packages/dev/src/commands/restore.tsindex 29f9a481ee..f24e764116 100644--- a/packages/dev/src/commands/restore.ts+++ b/packages/dev/src/commands/restore.ts@@ -9,13 +9,14 @@ import { execa } from "execa";import { isAbsolute, join, resolve } from "pathe";import { requireNumberEnv, tryConnect } from "../helpers.js";import { confirmRestore } from "../prompts.js";+import { wakeIfAsleep } from "../services/hibernate.js";import {applyMigrations,serviceSchemasReady,syncAuthz} from "../services/migrations.js";import { tasks } from "../ui.js";-import { getWorktreeRoot } from "../worktree.js";+import { getWorktreeRoot, resolveSlug } from "../worktree.js";export type RestoreMode = "local" | "prod";@@ -116,6 +117,7 @@ export async function restore(opts: RestoreOptions) {// postgres-only stack the dump's `CREATE TABLE auth.users` no-ops onto the// image's stub, and the restore fails late — after the data has landed but// before the email scrub — leaving unscrubbed production addresses on disk.+ await wakeIfAsleep(resolveSlug(root));if (!(await tryConnect("127.0.0.1", portDb, 500))) {cancel("postgres is not reachable — run `crbn up` first, then retry");process.exit(1);diff --git a/packages/dev/src/commands/status.ts b/packages/dev/src/commands/status.tsindex 7b1ce250a9..d2189d1f37 100644--- a/packages/dev/src/commands/status.ts+++ b/packages/dev/src/commands/status.ts@@ -5,6 +5,7 @@import { intro, log, outro } from "@clack/prompts";import pc from "picocolors";import { listContainers } from "../services/compose.js";+import { isAsleep } from "../services/hibernate.js";import { portsTable, servicesTable } from "../ui.js";import {getSlot,@@ -44,6 +45,10 @@ export async function status(opts: { json?: boolean } = {}) {symbol: pc.bold(pc.yellow("Portless"))});+ if (isAsleep(slug)) {+ log.info("hibernated — the next ERP/MES request wakes it");+ }+const containers = await listContainers(root, slug);if (containers.length === 0) {log.warn("no containers running");diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex c914ac21fb..094cd2231d 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -2,14 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { writeFileSync } from "node:fs";import { box, intro, log, outro } from "@clack/prompts";import { config as loadDotenv } from "dotenv";import { type ExecaChildProcess, execa } from "execa";import { join } from "pathe";+import pc from "picocolors";import { APP_CHOICES, type AppId } from "../constants.js";import { renderEnv, syncAppPortlessConfigs, writeEnv } from "../env.js";import { currentBranch } from "../git.js";-import { onShutdown } from "../helpers.js";+import { onShutdown, tryConnect } from "../helpers.js";import { pickApps, pickBorrowSlug } from "../prompts.js";import {assemblerDepsBuilt,@@ -36,14 +38,22 @@ import {pullStack,restartServices,type StackSize,+ sleepStack,tailServiceLogs} from "../services/compose.js";+import {+ activityFile,+ stackStateDir,+ startWaker,+ watchIdle+} from "../services/hibernate.js";import {applyBootstrapSql,applyMigrations,ensureConfigRow,ensureSmokeTestUser,syncAuthz,+ waitForApi,waitForPostgres,waitForServiceSchemas,waitForStorageReady,@@ -106,6 +116,8 @@ type UpOpts = {minimal?: boolean;/** Also start Studio, Postgres-Meta and the edge runtime. */full?: boolean;+ /** Stop the containers while ERP/MES get no traffic (default true). */+ hibernate?: boolean;};type Ctx = {@@ -197,8 +209,9 @@ export async function up(opts: UpOpts = {}) {let borrowedEntry:| { ports: PortMap; redisDb: number; jwt: JwtCreds }| undefined;+ let borrowSlug: string | undefined;if (shouldBorrow) {- const borrowSlug = await pickBorrowSlug(slug);+ borrowSlug = await pickBorrowSlug(slug);const entry = getSlot(borrowSlug);if (!entry)throw new Error(@@ -300,15 +313,108 @@ export async function up(opts: UpOpts = {}) {return;}outro("apps starting (Ctrl+C to stop)");- await runAppsThenTeardown(- root,- selectedApps,- ctx.ports,- portless,- stripeChild- );++ // The dev servers report traffic for the stack they talk to — the borrowed+ // one under --borrow, whose own `crbn up` does the hibernating.+ const stateDir = stackStateDir(borrowSlug ?? slug);+ process.env.CRBN_STACK_STATE = stateDir;+ const idleMinutes = Number(process.env.CRBN_IDLE_MINUTES ?? 30);+ const hibernates =+ opts.hibernate !== false &&+ !borrowSlug &&+ idleMinutes > 0 &&+ reactRouterApps(selectedApps).length > 0;+ // Deep sleep parks the dev servers: the watcher aborts them, listens on+ // their ports itself, and on the next request starts the containers and lets+ // the app loop below spawn them again.+ const deepMinutes = Number(process.env.CRBN_APPS_IDLE_MINUTES ?? 120);+ const appPorts = reactRouterApps(selectedApps).flatMap((id) => {+ const key = APP_PORT_KEY[id];+ return key ? [ctx.ports[key]] : [];+ });+ const parking: AppParking = { parked: false };+ let wakers: Array<() => Promise<void>> = [];+ let tearingDown = false;+ const wakeContainers = async () => {+ await bootStack(root, slug, size);+ await waitForPostgres(ctx.ports.PORT_DB);+ await waitForApi(ctx.ports.PORT_API, ctx.jwt.anonKey);+ };+ const stopWatching = hibernates+ ? watchIdle({+ dir: stateDir,+ idleMs: idleMinutes * 60_000,+ deepMs: deepMinutes * 60_000,+ sleep: () => sleepStack(root, slug),+ deepen: async () => {+ parking.parked = true;+ parking.stop?.abort();+ await parking.exited;+ wakers = appPorts.map((port) =>+ startWaker(port, () => writeFileSync(activityFile(stateDir), ""))+ );+ },+ wake: async (from) => {+ try {+ await wakeContainers();+ } finally {+ // Whatever happened to the containers, never leave the apps+ // parked behind a listener that can no longer wake them.+ if (from === "deep") {+ await Promise.all(wakers.map((stop) => stop()));+ wakers = [];+ parking.parked = false;+ parking.resume?.();+ // Awake means the dev servers are listening again: until then+ // no request can reach them, and the idle clock must not run.+ // Unless the stack is being torn down — nothing will listen.+ const deadline = Date.now() + 180_000;+ while (!tearingDown && Date.now() < deadline) {+ const open = await Promise.all(+ appPorts.map((port) => tryConnect("127.0.0.1", port, 500))+ );+ if (open.every(Boolean)) break;+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ }+ }+ },+ log: (line) => process.stderr.write(`${pc.cyan("•")} ${line}\n`)+ })+ : undefined;+ // Before `down()`, not after it: a request (the waking page polls every+ // 1.5 s) can start a wake at any moment, and one that ran during or after+ // the teardown would leave the containers up with no `crbn up` owning them.+ const stopHibernation = async () => {+ tearingDown = true;+ await stopWatching?.();+ await Promise.all(wakers.map((stop) => stop()));+ wakers = [];+ };+ try {+ await runAppsThenTeardown(+ root,+ selectedApps,+ ctx.ports,+ portless,+ stripeChild,+ parking,+ stopHibernation+ );+ } finally {+ await stopHibernation();+ }}+// Shared between the idle watcher and the app loop. `parked` means the dev+// servers were stopped on purpose and will be started again.+type AppParking = {+ parked: boolean;+ stop?: AbortController;+ exited?: Promise<void>;+ resume?: () => void;+};+// Kill the detached stripe listener's whole process group (apps-mode teardown).function killStripe(child?: ExecaChildProcess) {if (!child?.pid) return;@@ -686,9 +792,12 @@ async function runAppsThenTeardown(selectedApps: AppId[],ports: PortMap,portless: boolean,- stripeChild?: ExecaChildProcess+ stripeChild?: ExecaChildProcess,+ parking: AppParking = { parked: false },+ beforeTeardown?: () => Promise<void>) {const apps = reactRouterApps(selectedApps);+ let detachParked: (() => void) | undefined;if (apps.length === 0) {await Promise.race([new Promise<void>((resolve) => {@@ -697,7 +806,33 @@ async function runAppsThenTeardown(whenAuxAppExits()]);} else {- await spawnApps({ root, apps, ports, portless });+ for (;;) {+ parking.stop = new AbortController();+ parking.exited = spawnApps({+ root,+ apps,+ ports,+ portless,+ signal: parking.stop.signal+ });+ await parking.exited;+ // Exited on their own or on Ctrl+C: tear down. Parked: wait for the+ // wake (or a Ctrl+C, which spawnApps is no longer listening for).+ if (!parking.parked) break;+ const interrupted = await new Promise<boolean>((resolve) => {+ // The listener is NOT removed from inside the signal: execa's cleanup+ // hook re-raises a signal it finds nobody else listening for, and a+ // wake has a docker child running. It stays until the teardown+ // listener below is in place.+ detachParked = onShutdown(() => resolve(true));+ parking.resume = () => {+ detachParked?.();+ detachParked = undefined;+ resolve(false);+ };+ });+ if (interrupted) break;+ }}// Apps exit on Ctrl+C; auto-`down` so compose stack isn't orphaned.@@ -706,7 +841,9 @@ async function runAppsThenTeardown(const detach = onShutdown(() => {process.stderr.write("\nfinishing teardown — please wait\n");});+ detachParked?.();try {+ await beforeTeardown?.();// Kill the stripe listener too — it's detached and would otherwise survive.killStripe(stripeChild);// silent: post-SIGINT stdin raw-mode triggers EIO in clack's spinner.diff --git a/packages/dev/src/git.ts b/packages/dev/src/git.tsindex 57ea9533ac..51b8dbe51d 100644--- a/packages/dev/src/git.ts+++ b/packages/dev/src/git.ts@@ -90,6 +90,19 @@ export async function addWorktree(opts: {}}+// Remove a worktree only if git agrees it is clean. Unlike `removeWorktree`+// there is no fallback: git refusing means there is work in it (or it is+// locked), and that is the answer. Returns whether it was removed.+export async function removeCleanWorktree(path: string): Promise<boolean> {+ const r = await execa("git", ["worktree", "remove", path], { reject: false });+ return r.exitCode === 0;+}++// Drop git's records of worktrees whose directory no longer exists.+export async function pruneWorktreeEntries(): Promise<void> {+ await execa("git", ["worktree", "prune"], { reject: false });+}+export async function removeWorktree(path: string,force = falsediff --git a/packages/dev/src/main.ts b/packages/dev/src/main.tsindex 2bf2f3b73c..7a8f4d1c0b 100644--- a/packages/dev/src/main.ts+++ b/packages/dev/src/main.ts@@ -89,6 +89,12 @@ const main = defineCommand({default: false,description:"Also skip Inbucket, for headless/CI builds that sign in by bypass"+ },+ hibernate: {+ type: "boolean",+ default: true,+ description:+ "Stop the containers after 30 min without ERP/MES traffic, and the dev servers after 2 h; the next request starts them again (--no-hibernate to keep them up; CRBN_IDLE_MINUTES / CRBN_APPS_IDLE_MINUTES change the waits)"}},run: ({ args }) =>@@ -103,7 +109,8 @@ const main = defineCommand({run: typeof args.run === "string" ? args.run : undefined,volumes: args.volumes === true,full: args.full === true,- minimal: args.minimal === true+ minimal: args.minimal === true,+ hibernate: args.hibernate !== false})}),down: defineCommand({@@ -361,9 +368,16 @@ const main = defineCommand({default: false,description:"Destroy EVERY crbn stack on this machine, running ones included. Worktrees, branches and live slots are kept; the next `crbn up` rebuilds the database"+ },+ tree: {+ type: "boolean",+ default: false,+ description:+ "Also clean up git worktrees: forget ones whose directory is gone; with --all, remove this repo's linked worktrees too (never the main checkout, the current one, or one with uncommitted changes; branches are kept)"}},- run: ({ args }) => prune({ all: args.all === true })+ run: ({ args }) =>+ prune({ all: args.all === true, tree: args.tree === true })}),copy: defineCommand({meta: {diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.tsindex 8610f0e9c4..932fb8cb11 100644--- a/packages/dev/src/prompts.ts+++ b/packages/dev/src/prompts.ts@@ -32,7 +32,9 @@ const INVALID_BRANCH_RE =// ends mid-command. Say what was needed, and how to run without a terminal.export function requireTerminal(what: string, instead: string) {if (process.stdin.isTTY) return;- throw new Error(`${what} needs a terminal. ${instead}`);+ // Not a throw: citty prints a thrown error with its stack, twice.+ cancel(`${what} needs a terminal. ${instead}`);+ process.exit(1);}const CONFIRM_BY_ENV = "Set CARBON_DEV_YES=1 to confirm without one.";@@ -220,11 +222,19 @@ export async function confirmReset(projectName: string): Promise<boolean> {return ok as boolean;}-export async function confirmPrune(count: number): Promise<boolean> {+export async function confirmPrune(count: number, trees = 0): Promise<boolean> {if (process.env.CARBON_DEV_YES === "1") return true;requireTerminal("Confirming a prune", CONFIRM_BY_ENV);const ok = await confirm({- message: `Destroy ${count} stack(s) and their volumes? (postgres, storage, inngest data will be wiped)`,+ // Only what will happen: a worktree-only prune wipes no data.+ message: `${[+ count+ ? `Destroy ${count} stack(s) and their volumes (postgres, storage, inngest data will be wiped)`+ : "",+ trees ? `${count ? "remove" : "Remove"} ${trees} worktree(s)` : ""+ ]+ .filter(Boolean)+ .join(", and ")}?`,initialValue: false});if (isCancel(ok)) return false;diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.tsindex 5f1ca01ef0..137dc61a75 100644--- a/packages/dev/src/services/compose.ts+++ b/packages/dev/src/services/compose.ts@@ -113,6 +113,17 @@ export async function bootStack(await execStrict("docker", buildUpArgs(root, slug, opts), root);}+// Stop every container of the stack but keep them (and their volumes): the+// memory is freed and `bootStack` brings them back. All profiles, so a service+// started later with `crbn reload` is stopped too. 30s for Postgres to shut+// down cleanly before Docker kills it.+export async function sleepStack(root: string, slug: string) {+ const args = devArgs(root, slug, ...envFileArgs(root));+ for (const profile of COMPOSE_PROFILES) args.push("--profile", profile);+ args.push("stop", "--timeout", "30");+ await execStrict("docker", args, root);+}+// `docker compose restart` a subset of services. Used by the storage-stuck// heal path: after re-applying init.sql we restart storage/gotrue/postgrest so// they reconnect with the freshly-rotated supabase role passwords.diff --git a/packages/dev/src/services/hibernate.test.ts b/packages/dev/src/services/hibernate.test.tsnew file mode 100644index 0000000000..b49cbd7d1d--- /dev/null+++ b/packages/dev/src/services/hibernate.test.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { nextStep } from "./hibernate.js";++const IDLE = 30 * 60_000;++describe("nextStep", () => {+ it("sleeps only once the quiet spell reaches the limit", () => {+ expect(nextStep("awake", IDLE - 1, 0, 0, IDLE)).toBeNull();+ expect(nextStep("awake", IDLE, 0, 0, IDLE)).toBe("sleep");+ });++ it("stops the dev servers only after the longer limit, and only from asleep", () => {+ const DEEP = 4 * IDLE;+ expect(nextStep("asleep", DEEP - 1, 0, IDLE, IDLE, DEEP)).toBeNull();+ expect(nextStep("asleep", DEEP, 0, IDLE, IDLE, DEEP)).toBe("deepen");+ expect(nextStep("deep", 2 * DEEP, 0, DEEP, IDLE, DEEP)).toBeNull();+ expect(nextStep("deep", 2 * DEEP, DEEP + 1, DEEP, IDLE, DEEP)).toBe("wake");+ expect(nextStep("asleep", DEEP, 0, IDLE, IDLE, 0)).toBeNull();+ });++ it("stays asleep until a request lands after it went to sleep", () => {+ expect(nextStep("asleep", 5000, 900, 1000, IDLE)).toBeNull();+ expect(nextStep("asleep", 5000, 1001, 1000, IDLE)).toBe("wake");+ });+});diff --git a/packages/dev/src/services/hibernate.ts b/packages/dev/src/services/hibernate.tsnew file mode 100644index 0000000000..bc87d19fa3--- /dev/null+++ b/packages/dev/src/services/hibernate.ts@@ -0,0 +1,260 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ existsSync,+ mkdirSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync+} from "node:fs";+import { createServer } from "node:http";+import { homedir } from "node:os";+import { setTimeout as sleep } from "node:timers/promises";+import { join } from "pathe";++// A stack whose apps nobody is using still holds ~1 GB. The ERP and MES dev+// servers report each request by touching `activity` (the `stackActivity` Vite+// plugin); `crbn up` stops the containers after a quiet spell and leaves an+// `asleep` marker. The plugin holds the next request while the marker exists,+// and its touch is what tells this watcher to start the containers again.+// The dev servers keep running at first: they are what receives the request+// that wakes the stack, and the wake costs seconds.+//+// They hold more memory than the containers, though (about 1.1 GB each+// against 0.9 GB for the stack), so after a much longer quiet spell `crbn up`+// stops them as well and listens on their ports itself (`startWaker`). That+// wake is slower: the dev servers boot from cold.+//+// Keyed by slug, not worktree, so a `--borrow`ing worktree reports to the+// stack it is actually using.+export function stackStateDir(slug: string): string {+ return join(homedir(), ".carbon", "stacks", slug);+}++export const activityFile = (dir: string) => join(dir, "activity");+export const asleepFile = (dir: string) => join(dir, "asleep");++export type StackState = "awake" | "asleep" | "deep";+export type Step = "sleep" | "deepen" | "wake";++// Exported for tests. `since` is when the current state began: a request held+// during the stop touches `activity` after it, and that is the wake signal.+export function nextStep(+ state: StackState,+ now: number,+ lastActivity: number,+ since: number,+ idleMs: number,+ // 0: never stop the dev servers.+ deepMs = 0+): Step | null {+ if (state === "awake") return now - lastActivity >= idleMs ? "sleep" : null;+ if (lastActivity > since) return "wake";+ if (state === "asleep" && deepMs > 0 && now - lastActivity >= deepMs)+ return "deepen";+ return null;+}++function mtime(file: string): number {+ try {+ return statSync(file).mtimeMs;+ } catch {+ return 0;+ }+}++export function watchIdle(opts: {+ dir: string;+ idleMs: number;+ deepMs?: number;+ sleep: () => Promise<void>;+ /** Stop the dev servers too; the stack is already asleep. */+ deepen?: () => Promise<void>;+ wake: (from: StackState) => Promise<void>;+ log: (line: string) => void;+}): () => Promise<void> {+ const { dir, idleMs, log } = opts;+ const deepMs = opts.deepen ? (opts.deepMs ?? 0) : 0;+ const minutes = (ms: number) => Math.round(ms / 60_000);+ mkdirSync(dir, { recursive: true });+ rmSync(asleepFile(dir), { force: true });+ writeFileSync(activityFile(dir), "");++ let state: StackState = "awake";+ let since = Date.now();+ let busy = false;+ let stopped = false;+ let inFlight: Promise<void> = Promise.resolve();++ const tick = async () => {+ if (busy || stopped) return;+ const step = nextStep(+ state,+ Date.now(),+ mtime(activityFile(dir)),+ since,+ idleMs,+ deepMs+ );+ if (!step) return;+ busy = true;+ try {+ if (step === "sleep") {+ // Marker first: a request that arrives mid-stop must be held, not+ // served against half-stopped containers.+ since = Date.now();+ writeFileSync(asleepFile(dir), String(process.pid));+ state = "asleep";+ await opts.sleep();+ log(+ `stack hibernated after ${minutes(idleMs)} min without ERP/MES traffic — the next request wakes it`+ );+ } else if (step === "deepen") {+ state = "deep";+ await opts.deepen?.();+ log(+ `dev servers stopped after ${minutes(deepMs)} min idle — the next request starts them again (slower: they boot from cold)`+ );+ } else {+ const from = state;+ const started = Date.now();+ log("request received — waking the stack");+ await opts.wake(from);+ log(`stack awake (${Math.round((Date.now() - started) / 1000)}s)`);+ state = "awake";+ since = Date.now();+ writeFileSync(activityFile(dir), "");+ rmSync(asleepFile(dir), { force: true });+ }+ } catch (err) {+ // Let held requests through to fail visibly rather than hang, and keep+ // watching: the next quiet spell or request tries again.+ log(`hibernation ${step} failed: ${(err as Error).message}`);+ state = "awake";+ since = Date.now();+ writeFileSync(activityFile(dir), "");+ rmSync(asleepFile(dir), { force: true });+ } finally {+ busy = false;+ }+ };++ // Only a tick that can start a step replaces `inFlight`: one that returns at+ // once because a step is running must not hide that step from the disposer.+ const timer = setInterval(() => {+ if (!busy) inFlight = tick();+ }, 1000);+ // Resolves once a step that was already running has finished: the caller+ // tears the stack down next, and a wake still in progress would start the+ // containers again behind it.+ return async () => {+ stopped = true;+ clearInterval(timer);+ await inFlight;+ rmSync(asleepFile(dir), { force: true });+ };+}++// The marker holds the pid of the `crbn up` that will do the waking. One that+// was killed leaves its marker behind with nobody to act on it.+export function isAsleep(slug: string): boolean {+ const marker = asleepFile(stackStateDir(slug));+ if (!existsSync(marker)) return false;+ try {+ process.kill(Number(readFileSync(marker, "utf8")), 0);+ return true;+ } catch {+ rmSync(marker, { force: true });+ return false;+ }+}++// For crbn commands that need the database: ask the watching `crbn up` to+// start the stack the same way a request does, and wait for it.+export async function wakeIfAsleep(+ slug: string,+ timeoutMs = 120_000+): Promise<boolean> {+ if (!isAsleep(slug)) return false;+ const dir = stackStateDir(slug);+ writeFileSync(activityFile(dir), "");+ const deadline = Date.now() + timeoutMs;+ while (isAsleep(slug)) {+ if (Date.now() > deadline) {+ throw new Error(+ "the stack is hibernated and did not wake — check the terminal running `crbn up`"+ );+ }+ await sleep(250);+ }+ return true;+}++// What a browser sees while the dev servers boot. The script keeps asking for+// the same URL — through the moment the port is closed between this listener+// stopping and the dev server binding it — and reloads once a response comes+// back without the waking header.+const WAKING_PAGE = `<!doctype html><meta charset="utf-8"><title>Waking…</title>+<body style="font:15px system-ui;display:grid;place-items:center;height:100vh;margin:0;color:#666">+<p>Waking the dev stack — this page reloads when it is ready.</p>+<script>+let busy = false;+setInterval(async () => {+ if (busy) return;+ busy = true;+ try {+ const res = await fetch(location.href, { cache: "no-store" });+ if (!res.headers.get("x-crbn-waking")) location.reload();+ } catch {}+ busy = false;+}, 1500);+</script>`;++// Stands in for a stopped dev server on its port. A request is the signal to+// wake; it cannot be handed to the dev server (which needs this very port), so+// a browser gets a page that waits and reloads, and anything else a 503.+// Not traffic: Inngest's poll, and the Vite client of an open tab probing for+// its server over a WebSocket — answering those would wake the stack the+// moment it went to sleep.+export function startWaker(port: number, onWake: () => void) {+ const server = createServer((req, res) => {+ if (req.url?.startsWith("/api/inngest")) {+ res.writeHead(503).end();+ return;+ }+ onWake();+ const html = req.headers.accept?.includes("text/html");+ res.writeHead(503, {+ "content-type": html ? "text/html; charset=utf-8" : "application/json",+ "cache-control": "no-store",+ "retry-after": "5",+ "x-crbn-waking": "1"+ });+ res.end(html ? WAKING_PAGE : '{"error":"dev stack is waking"}');+ });+ server.on("upgrade", (_req, socket) => socket.destroy());+ // The dev server's process tree can hold the port for a moment after its+ // parent has exited; keep trying until it lets go.+ let stopped = false;+ let retry: NodeJS.Timeout | undefined;+ server.on("error", () => {+ if (stopped) return;+ retry = setTimeout(() => {+ if (!stopped) server.listen(port, "127.0.0.1");+ }, 250);+ });+ server.listen(port, "127.0.0.1");+ return () =>+ new Promise<void>((resolve) => {+ // A retry left pending would bind the port after the stop and keep the+ // respawned dev server off it.+ stopped = true;+ clearTimeout(retry);+ server.closeAllConnections();+ if (server.listening) server.close(() => resolve());+ else resolve();+ });+}diff --git a/packages/dev/src/services/migrations.ts b/packages/dev/src/services/migrations.tsindex 24269bdbe6..4d6a6495b2 100644--- a/packages/dev/src/services/migrations.ts+++ b/packages/dev/src/services/migrations.ts@@ -55,6 +55,33 @@ export async function waitForPostgres(port: number, timeoutMs = 60_000) {throw new Error(`postgres did not accept queries within ${timeoutMs}ms`);}+// Block until Kong answers for both PostgREST and GoTrue. After a hibernated+// stack is started again the ports open well before these two can serve, and+// the request that woke the stack is waiting on exactly them.+export async function waitForApi(+ port: number,+ anonKey: string,+ timeoutMs = 60_000+) {+ const deadline = Date.now() + timeoutMs;+ const up = async (path: string) => {+ try {+ const res = await fetch(`http://127.0.0.1:${port}${path}`, {+ headers: { apikey: anonKey },+ signal: AbortSignal.timeout(2000)+ });+ return res.ok;+ } catch {+ return false;+ }+ };+ while (Date.now() < deadline) {+ if ((await up("/rest/v1/")) && (await up("/auth/v1/health"))) return;+ await sleep(500);+ }+ throw new Error(`the API did not answer within ${timeoutMs}ms`);+}+/*** Block until supabase storage-api has bootstrapped `storage.buckets`. Probes* for 30s first; if missing, invokes `onHeal` (re-apply init.sql + restartdiff --git a/packages/dev/src/services/portless.test.ts b/packages/dev/src/services/portless.test.tsnew file mode 100644index 0000000000..b39fe5f572--- /dev/null+++ b/packages/dev/src/services/portless.test.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { staleAliasNames } from "./portless.js";++describe("staleAliasNames", () => {+ const live = new Set([5000]);++ it("returns crbn aliases whose port no live slot owns", () => {+ const routes = [+ { hostname: "erp.gone.dev", port: 4000, pid: 0 },+ { hostname: "api.gone.dev", port: 4001, pid: 0 }+ ];+ expect(staleAliasNames(routes, live)).toEqual(["erp.gone", "api.gone"]);+ });++ it("keeps live routes, running processes and routes crbn did not register", () => {+ const routes = [+ { hostname: "erp.live.dev", port: 5000, pid: 0 },+ { hostname: "erp.running.dev", port: 4000, pid: 1234 },+ { hostname: "myapp.gone.dev", port: 4000, pid: 0 },+ { hostname: "erp.gone.localhost", port: 4000, pid: 0 }+ ];+ expect(staleAliasNames(routes, live)).toEqual([]);+ });+});diff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.tsindex 3a4a273688..89c9e30516 100644--- a/packages/dev/src/services/portless.ts+++ b/packages/dev/src/services/portless.ts@@ -7,8 +7,9 @@ import { homedir } from "node:os";import { setTimeout as sleep } from "node:timers/promises";import { confirm, isCancel, log } from "@clack/prompts";import { execa, execaSync } from "execa";+import { join } from "pathe";import pc from "picocolors";-import { PORTLESS_MIN_VERSION } from "../constants.js";+import { PORTLESS_MIN_VERSION, TLD } from "../constants.js";import { requireTerminal } from "../prompts.js";import { spinner } from "../ui.js";import type { PortMap } from "../worktree.js";@@ -377,6 +378,57 @@ export async function unregisterAliases(root: string, branchPrefix: string) {);}+type Route = { hostname: string; port: number; pid: number };++// Static aliases (pid 0) crbn registered whose port no live slot owns: the+// stack they pointed at is gone, and `portless prune` only reaps routes that+// have a process. Returned as alias names (hostname minus the TLD). Exported+// for tests.+export function staleAliasNames(+ routes: Route[],+ livePorts: Set<number>+): string[] {+ const suffix = `.${TLD}`;+ // The first label of every hostname crbn registers.+ const labels = new Set(+ aliasMap("x", {} as PortMap).map((a) => a.name.split(".")[0])+ );+ return routes+ .filter(+ (r) =>+ r.pid === 0 &&+ r.hostname.endsWith(suffix) &&+ labels.has(r.hostname.split(".")[0]) &&+ !livePorts.has(r.port)+ )+ .map((r) => r.hostname.slice(0, -suffix.length));+}++export function findStaleAliases(livePorts: Set<number>): string[] {+ const file = join(+ process.env.PORTLESS_STATE_DIR ?? join(homedir(), ".portless"),+ "routes.json"+ );+ if (!existsSync(file)) return [];+ try {+ return staleAliasNames(JSON.parse(readFileSync(file, "utf8")), livePorts);+ } catch {+ return [];+ }+}++// One at a time: each call rewrites portless's routes file.+export async function removeAliases(names: string[]) {+ for (const name of names) {+ await execa("portless", ["alias", "--remove", name], {+ reject: false,+ stdio: "ignore",+ extendEnv: false,+ env: portlessEnv()+ });+ }+}+// Let portless handle its own cleanup — kills orphaned dev servers from// crashed sessions and removes their stale route entries.export async function pruneStaleRoutes() {diff --git a/packages/dev/src/ui.test.ts b/packages/dev/src/ui.test.tsnew file mode 100644index 0000000000..4a09847f1c--- /dev/null+++ b/packages/dev/src/ui.test.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { worktreesTable } from "./ui.js";++const rows = [+ {+ path: "/work/carbon/.claude/worktrees/a-long-worktree-directory-name",+ branch: "feat/a-long-branch-name",+ current: false,+ slug: "a-long-worktree-directory-name",+ dockerState: "running"+ }+];++describe("worktreesTable", () => {+ it("draws the table when it fits", () => {+ expect(worktreesTable(rows, 200)).toContain("┌");+ });++ it("stacks each worktree on two lines when the table is too wide", () => {+ const out = worktreesTable(rows, 60);+ expect(out).not.toContain("┌");+ expect(out.split("\n")).toHaveLength(2);+ expect(out).toContain("feat/a-long-branch-name");+ expect(out).toContain("a-long-worktree-directory-name");+ });+});diff --git a/packages/dev/src/ui.ts b/packages/dev/src/ui.tsindex 95e52b1670..23f0cae48d 100644--- a/packages/dev/src/ui.ts+++ b/packages/dev/src/ui.ts@@ -2,6 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { homedir } from "node:os";+import { stripVTControlCharacters } from "node:util";import {progress as clackProgress,spinner as clackSpinner,@@ -115,28 +117,44 @@ export function worktreesTable(current: boolean;slug: string | null;dockerState: string | null;- }[]+ }[],+ // Columns the table may use; clack's gutter takes four. A pipe has no width+ // and is never narrowed.+ width = process.stdout.columns ? process.stdout.columns - 4 : Infinity): string {const t = new Table({head: [pc.bold("Worktree"), pc.bold("Branch"), pc.bold("Stack")],...BASE_STYLE});+ const home = homedir();+ const stacked: string[] = [];for (const r of rows) {+ const path = r.path.startsWith(`${home}/`)+ ? `~${r.path.slice(home.length)}`+ : r.path;const project = r.slug ? projectName(r.slug) : "—";const stack = !r.slug? pc.gray("not initialized"): r.dockerState === "running"? pc.green(`● up · ${project}`)- : r.dockerState- ? pc.yellow(`${r.dockerState} · ${project}`)- : pc.dim(`registered · ${project}`);- t.push([- r.current ? pc.bold(pc.cyan(r.path)) : r.path,- r.branch ? pc.cyan(r.branch) : pc.dim("(detached)"),- stack- ]);+ : r.dockerState === "hibernated"+ ? pc.blue(`◌ hibernated · ${project}`)+ : r.dockerState+ ? pc.yellow(`${r.dockerState} · ${project}`)+ : pc.dim(`registered · ${project}`);+ const branch = r.branch ? pc.cyan(r.branch) : pc.dim("(detached)");+ t.push([r.current ? pc.bold(pc.cyan(path)) : path, branch, stack]);+ stacked.push(+ `${r.current ? pc.bold(branch) : branch} ${stack}\n ${pc.dim(path)}`+ );}- return t.toString();+ // A table wider than the terminal wraps mid-row and is unreadable; one+ // worktree per two lines reads at any width.+ const table = t.toString();+ const widest = Math.max(+ ...table.split("\n").map((line) => stripVTControlCharacters(line).length)+ );+ return widest <= width ? table : stacked.join("\n");}function colorState(state: string, health: string | null): string {diff --git a/packages/dev/vite.d.ts b/packages/dev/vite.d.tsindex 165c5dcea7..812c94315d 100644--- a/packages/dev/vite.d.ts+++ b/packages/dev/vite.d.ts@@ -6,5 +6,6 @@ import type { Plugin } from "vite";export function applyDotenvToProcessEnv(mode: string, appDir: string): void;export function clientOnlyAlias(specifier: string, file: string): Plugin;+export function stackActivity(): Plugin;export function linguiWithoutIdQuery<T>(plugins: T[]): T[];diff --git a/packages/dev/vite.js b/packages/dev/vite.jsindex 9a50fff730..bb48b7b4cd 100644--- a/packages/dev/vite.js+++ b/packages/dev/vite.js@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import fs from "node:fs";import path from "node:path";import { loadEnv } from "vite";@@ -83,3 +84,51 @@ export function linguiWithoutIdQuery(plugins) {};});}++/**+ * Dev-server half of stack hibernation (see `services/hibernate.ts` in this+ * package). Touches `activity` on each request so `crbn up` can tell the apps+ * are in use, and holds a request while the stack is asleep until `crbn up`+ * has started the containers again. Does nothing unless `crbn up` set+ * `CRBN_STACK_STATE`, so a build or a bare `vite dev` is unaffected.+ *+ * `/api/inngest` is not traffic: the Inngest dev server polls it constantly+ * and would keep every stack awake.+ *+ * @returns {import("vite").Plugin}+ */+export function stackActivity() {+ return {+ name: "carbon:stack-activity",+ apply: "serve",+ configureServer(server) {+ const dir = process.env.CRBN_STACK_STATE;+ if (!dir) return;+ const activity = path.join(dir, "activity");+ const asleep = path.join(dir, "asleep");+ let touched = 0;+ const touch = (force) => {+ const now = Date.now();+ if (!force && now - touched < 2000) return;+ touched = now;+ try {+ fs.writeFileSync(activity, "");+ } catch {+ // crbn up is gone; nothing is watching+ }+ };+ server.middlewares.use(async (req, _res, next) => {+ if (req.url?.startsWith("/api/inngest")) return next();+ touch(false);+ if (fs.existsSync(asleep)) {+ touch(true);+ const deadline = Date.now() + 120_000;+ while (fs.existsSync(asleep) && Date.now() < deadline) {+ await new Promise((resolve) => setTimeout(resolve, 200));+ }+ }+ next();+ });+ },+ };+}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 3ca770baa1..05d2ed379b 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -19619,9 +19619,6 @@ msgstr "Verfolgte Materialien werden nach Kommissionierauftrag vorabausgewähltmsgid "Tracking"msgstr "Verfolgung"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Verfolgungsmethode"@@ -20009,6 +20006,9 @@ msgstr "Unbenannte Zeile"msgid "Untitled step"msgstr "Unbenannter Schritt"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Ungenutzte kommissionierte Materialien werden vom Arbeitsplatz zurück ins Lager geleitet."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex eec6a62ceb..4c2b14b887 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -19619,9 +19619,6 @@ msgstr "Tracked material is pre-selected by pick order (FEFO), even without a pimsgid "Tracking"msgstr "Tracking"-msgid "Tracking ID"-msgstr "Tracking ID"-msgid "Tracking method"msgstr "Tracking method"@@ -20009,6 +20006,9 @@ msgstr "Untitled line"msgid "Untitled step"msgstr "Untitled step"+msgid "Untracked"+msgstr "Untracked"+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Unused picked material flushed back from the work center to the warehouse."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 7d9db133c5..2a7403746e 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -19619,9 +19619,6 @@ msgstr "El material rastreado se preselecciona por orden de picking (FEFO), inclmsgid "Tracking"msgstr "Seguimiento"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Método de seguimiento"@@ -20009,6 +20006,9 @@ msgstr "Línea sin título"msgid "Untitled step"msgstr "Paso sin título"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Material recogido no utilizado devuelto desde el centro de trabajo al almacén."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 78a21e81d3..45483a49f2 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -19619,9 +19619,6 @@ msgstr "Le matériel suivi est pré-sélectionné par ordre de prélèvement (FEmsgid "Tracking"msgstr "Suivi"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Méthode de suivi"@@ -20009,6 +20006,9 @@ msgstr "Ligne sans titre"msgid "Untitled step"msgstr "Étape sans titre"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Matière prélevée inutilisée renvoyée du poste de travail à l'entrepôt."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex cb5f4b5910..fcace9b760 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -19619,9 +19619,6 @@ msgstr "ट्रैक की गई सामग्री को पिकिmsgid "Tracking"msgstr "ट्रैकिंग"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "ट्रैकिंग विधि"@@ -20009,6 +20006,9 @@ msgstr "बिना शीर्षक की पंक्ति"msgid "Untitled step"msgstr "बिना शीर्षक वाला चरण"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "अप्रयुक्त सामग्री को वर्क सेंटर से गोदाम में वापस भेजा गया।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex e9944def61..bb4a450f13 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -19619,9 +19619,6 @@ msgstr "Il materiale tracciato è preselezionato per ordine di prelievo (FEFO),msgid "Tracking"msgstr "Tracciamento"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Metodo di tracciamento"@@ -20009,6 +20006,9 @@ msgstr "Riga senza titolo"msgid "Untitled step"msgstr "Passo senza titolo"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Materiale prelevato non utilizzato reso dal centro di lavoro al deposito."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex f994da97de..fdca37ccdc 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -19619,9 +19619,6 @@ msgstr "追跡される材料は、ピッキングリストがない場合でもmsgid "Tracking"msgstr "追跡"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "追跡方法"@@ -20009,6 +20006,9 @@ msgstr "無題の行"msgid "Untitled step"msgstr "無題のステップ"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "未使用のピッキング済み材料が作業区から倉庫に戻されました。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex b565633448..b21dc4b770 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -19619,9 +19619,6 @@ msgstr "추적 자재는 피킹 리스트가 없어도 피킹 순서(FEFO)에msgid "Tracking"msgstr "추적"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "추적 방법"@@ -20009,6 +20006,9 @@ msgstr "제목 없는 라인"msgid "Untitled step"msgstr "제목 없는 단계"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "작업장에서 창고로 반환된 미사용 선택 재료."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 03c1e30f3c..5c884d946c 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -19619,9 +19619,6 @@ msgstr "Materiał śledzony jest wstępnie wybierany według kolejności poborumsgid "Tracking"msgstr "Śledzenie"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Metoda śledzenia"@@ -20009,6 +20006,9 @@ msgstr "Linia bez tytułu"msgid "Untitled step"msgstr "Krok bez tytułu"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Materiał pobrany, ale nieużywany, zwracany ze stanowiska roboczego do magazynu."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 68c737bda1..0633349998 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -19619,9 +19619,6 @@ msgstr "Material rastreado é pré-selecionado por ordem de separação (FEFO),msgid "Tracking"msgstr "Rastreamento"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Método de rastreamento"@@ -20009,6 +20006,9 @@ msgstr "Linha sem título"msgid "Untitled step"msgstr "Etapa sem título"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Material coletado não utilizado devolvido do centro de trabalho para o armazém."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 9deed81b4c..30de6f64d6 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -19619,9 +19619,6 @@ msgstr "Отслеживаемый материал предварительноmsgid "Tracking"msgstr "Отслеживание"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "Метод отслеживания"@@ -20009,6 +20006,9 @@ msgstr "Безымянная строка"msgid "Untitled step"msgstr "Шаг без названия"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "Неиспользованный отобранный материал поступает обратно из рабочего центра на склад."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 873583cef7..49493a7eb1 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -19619,9 +19619,6 @@ msgstr "İzlenen malzeme, toplama listesi olmasa bile toplama sırasına (FEFO)msgid "Tracking"msgstr "Takip"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "İzleme yöntemi"@@ -20009,6 +20006,9 @@ msgstr "Başlıksız satır"msgid "Untitled step"msgstr "Başlıksız Adım"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "İş merkezinden depoya geri gönderilen kullanılmayan alınan malzeme."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 7d6a79190e..7e2e04fd68 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -19619,9 +19619,6 @@ msgstr "追踪原材料按拣货顺序(先到期先出)预选,即使没有msgid "Tracking"msgstr "追踪"-msgid "Tracking ID"-msgstr ""-msgid "Tracking method"msgstr "跟踪方法"@@ -20009,6 +20006,9 @@ msgstr "未命名行"msgid "Untitled step"msgstr "未命名步骤"+msgid "Untracked"+msgstr ""+msgid "Unused picked material flushed back from the work center to the warehouse."msgstr "未使用的已拣货物料从工作中心冲回至仓库。"diff --git a/packages/query/AGENTS.md b/packages/query/AGENTS.mdindex b7cecf4283..e36368b9ac 100644--- a/packages/query/AGENTS.md+++ b/packages/query/AGENTS.md@@ -42,7 +42,7 @@ pnpm --filter @carbon/query test| `createInvalidationMiddleware({ getCache, skipPaths })` | Root `clientMiddleware`; skip POSTs that change no data (`/refresh-session`) || `RouteRealtime`, `useRealtimeTable`, `useTableChanges`, `useRealtimeRevalidator` | Realtime over private broadcast topics. Revalidation waits for a submitting fetcher. A route entry `{ table, column, param }` and a `<name>Id=eq.` filter follow one record's rows only (`matchesFilter`) || `useRealtimeChannel` | One channel with retry, `private` and `onSubscribed(isReconnect)`. It reconnects when the tab returns after 5 minutes hidden or with a channel that is not joined — every reconnect reloads the page's data, so time in another tab does not |-| `LiveLists`, `useLiveList`, `LiveList` | Whole lists kept in the cache (items, customers, suppliers, people). IndexedDB first (the stored copy is keyed by company AND user: it is that user's RLS view); then `table_changes_since(cursor)` names the rows that changed since the stored copy and only those are re-read. The full list is fetched once per device, and again only when the log cannot answer (no cursor, a server restart, a cursor older than 7 days, more than 500 changed rows). Broadcasts patch it while the tab is open |+| `LiveLists`, `useLiveList`, `LiveList` | Whole lists kept in the cache (items, customers, suppliers, people). IndexedDB first (the stored copy is keyed by company AND user: it is that user's RLS view); then `table_changes_since(cursor)` names the rows that changed since the stored copy and only those are re-read. The full list is fetched once per device, and again only when the log cannot answer (no cursor, a server restart, a cursor older than 7 days, more than 500 changed rows). Broadcasts patch it in memory while the tab is open; the stored copy is written only when the log is read (a patch does not move the cursor, so storing it buys nothing). Stored lists are removed from the device when they are no longer the user's: another user's or a company outside `companyIds` at page load, the current company when `table_changes_since` answers `42501`, everything on the login page, and any list not written for 24 hours (`STORED_LIST_MAX_AGE_MS`). An open page repeats the check every hour and asks the log again, which rewrites its own lists and notices a user who has left the company |## Cross-Referencesdiff --git a/packages/query/src/liveList.test.ts b/packages/query/src/liveList.test.tsindex 5f1c66c3d5..6d1dd24844 100644--- a/packages/query/src/liveList.test.ts+++ b/packages/query/src/liveList.test.ts@@ -4,10 +4,16 @@import { describe, expect, it } from "vitest";import {+ expiredStoredKeys,type LoggedChanges,oldestCursor,planSync,removeRows,+ STORED_LIST_MAX_AGE_MS,+ staleStoredKeys,+ storedAtKey,+ storedListKey,+ storedListKeys,upsertRows} from "./liveList";@@ -83,3 +89,73 @@ describe("planSync", () => {expect(planSync(log({ customer: ids }), ["customer"], true)).toBe("all");});});++describe("staleStoredKeys", () => {+ const scope = {+ names: ["items", "customers"],+ userId: "u1",+ companyIds: ["c1", "c2"]+ };++ it("keeps the user's lists for the companies they belong to", () => {+ const keys = [+ storedListKey("c1", "u1", "items"),+ storedListKey("c2", "u1", "customers")+ ];+ expect(staleStoredKeys(keys, scope)).toEqual([]);+ });++ it("drops a company the user was removed from", () => {+ const gone = storedListKey("c3", "u1", "items");+ expect(+ staleStoredKeys([storedListKey("c1", "u1", "items"), gone], scope)+ ).toEqual([gone]);+ });++ it("drops another user's lists and copies stored before lists had an owner", () => {+ const other = storedListKey("c1", "u2", "items");+ expect(staleStoredKeys([other, "items:c1"], scope)).toEqual([+ other,+ "items:c1"+ ]);+ });++ it("leaves keys that are not a live list", () => {+ expect(staleStoredKeys(["search:c9:u9", "recent"], scope)).toEqual([]);+ });+});++describe("expiredStoredKeys", () => {+ const now = 1_800_000_000_000;++ it("keeps a list written within the last day", () => {+ expect(expiredStoredKeys([["items:c1:u1", now - 1000]], now)).toEqual([]);+ expect(+ expiredStoredKeys([["items:c1:u1", now - STORED_LIST_MAX_AGE_MS]], now)+ ).toEqual([]);+ });++ it("expires an older list, and one with no write time", () => {+ expect(+ expiredStoredKeys(+ [+ ["items:c1:u1", now - STORED_LIST_MAX_AGE_MS - 1],+ ["customers:c1:u1", null]+ ],+ now+ )+ ).toEqual(["items:c1:u1", "customers:c1:u1"]);+ });+});++describe("storedListKeys", () => {+ it("names the lists, not their write times or other keys", () => {+ const key = storedListKey("c1", "u1", "items");+ expect(+ storedListKeys(+ [key, storedAtKey(key), "search:c1:u1", "recent"],+ ["items"]+ )+ ).toEqual([key]);+ });+});diff --git a/packages/query/src/liveList.ts b/packages/query/src/liveList.tsindex 5e37a86c4b..b918c753d4 100644--- a/packages/query/src/liveList.ts+++ b/packages/query/src/liveList.ts@@ -83,3 +83,66 @@ export function upsertRows<Row extends { id: string }>(...fetched].sort(sort);}++/** The key a list is stored under on the device. */+export const storedListKey = (+ companyId: string,+ userId: string,+ name: string+) => `${name}:${companyId}:${userId}`;++/**+ * How long a stored list may stay on a device without being rewritten: it is+ * company data, so a copy nobody has refreshed for a day goes. An open page+ * rewrites its own lists every hour (`LiveLists`), so a list in use does not+ * expire under its reader.+ */+export const STORED_LIST_MAX_AGE_MS = 24 * 60 * 60 * 1000;++/** Where a stored list's write time is kept: beside it, so reading it is cheap. */+export const storedAtKey = (key: string) => `${key}:at`;++/** True for a stored list's own key, not the write time beside it. */+const isListKey = (key: string) => key.split(":").length === 3;++/**+ * The stored lists that are too old to keep, given each one's write time. A+ * list with no write time (stored before lists expired) counts as too old.+ */+export function expiredStoredKeys(+ storedAt: [key: string, at: unknown][],+ now: number+): string[] {+ return storedAt+ .filter(+ ([, at]) => typeof at !== "number" || now - at > STORED_LIST_MAX_AGE_MS+ )+ .map(([key]) => key);+}++/**+ * The stored lists this user may no longer hold: another user's, or a+ * company's the user does not belong to (removed from it since the copy was+ * taken). Keys that are not a live list are left alone; the store is shared.+ */+export function staleStoredKeys(+ keys: string[],+ {+ names,+ userId,+ companyIds+ }: { names: string[]; userId: string; companyIds: string[] }+): string[] {+ return keys.filter((key) => {+ const [name, companyId, owner] = key.split(":");+ if (!names.includes(name ?? "")) return false;+ return owner !== userId || !companyIds.includes(companyId ?? "");+ });+}++/** Of these keys, the stored lists named `names` (not their write times). */+export function storedListKeys(keys: string[], names: string[]): string[] {+ return keys.filter(+ (key) => isListKey(key) && names.includes(key.split(":")[0] ?? "")+ );+}diff --git a/packages/query/src/useLiveList.tsx b/packages/query/src/useLiveList.tsxindex 395a0cb7db..72601449d8 100644--- a/packages/query/src/useLiveList.tsx+++ b/packages/query/src/useLiveList.tsx@@ -12,10 +12,15 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";import { useCallback, useEffect, useRef } from "react";import {type Cursor,+ expiredStoredKeys,type LoggedChanges,oldestCursor,planSync,removeRows,+ staleStoredKeys,+ storedAtKey,+ storedListKey,+ storedListKeys,upsertRows} from "./liveList";import type { BroadcastChange } from "./useRealtime";@@ -68,6 +73,8 @@ type AnyRow = { id: string };export type LiveListStorage = {getItem: (key: string) => Promise<unknown>;setItem: (key: string, value: unknown) => Promise<unknown>;+ removeItem: (key: string) => Promise<unknown>;+ keys: () => Promise<string[]>;};type Stored = { rows: AnyRow[]; cursor: Cursor | null };@@ -84,8 +91,16 @@ const storageKey = (companyId: string, name: string) => `${name}:${companyId}`;// The stored copy also carries the user: it is that user's view of the list// (table RLS chose the rows), and the next person at this browser starts from// the server rather than from someone else's rows.-const storedKey = (companyId: string, userId: string, name: string) =>- `${storageKey(companyId, name)}:${userId}`;+const storedKey = storedListKey;++/** Remove a stored list and the write time kept beside it. */+// How often an open page checks its stored lists and asks the log again.+const BACKGROUND_CHECK_MS = 60 * 60 * 1000;++const forget = (idb: LiveListStorage, key: string) =>+ Promise.all([idb.removeItem(key), idb.removeItem(storedAtKey(key))]);+// What Postgres answers when `table_changes_since` refuses the caller.+const NOT_A_MEMBER = "42501";// A copy written before lists had a cursor is a bare array (or carries a// checksum instead): its rows are still good to show, with no cursor.@@ -149,11 +164,17 @@ function Subscription({export function LiveLists({companyId,userId,+ companyIds,lists,storage}: {companyId: string;userId: string;+ /**+ * Every company the user belongs to. Lists stored on this device for any+ * other company, or for another user, are removed when the page loads.+ */+ companyIds: string[];lists: AnyLiveList[];storage: () => Promise<LiveListStorage>;}) {@@ -163,6 +184,9 @@ export function LiveLists({// after a company switch belongs to the old company and is dropped.const active = useRef(companyId);active.current = companyId;+ // Read when the page loads; a new array each render must not reload the lists.+ const memberOf = useRef(companyIds);+ memberOf.current = companyIds;// Each list's cursor, per company (a company switch keeps this mounted):// where the change log is asked to start next time.const cursors = useRef(new Map<string, Cursor | null>());@@ -190,7 +214,8 @@ export function LiveLists({);/**- * Change a list's rows in the cache, then store them with the list's cursor.+ * Change a list's rows in the cache and, when the change log was read, store+ * them with the cursor it handed back.* The change is a function of the rows as they are NOW: two re-reads that* finish in either order both land, where a value computed before the read* would overwrite the other's rows.@@ -208,17 +233,20 @@ export function LiveLists({liveListKey(companyId, list.name),(current) => change(current ?? []));- if (cursor) cursors.current.set(storageKey(companyId, list.name), cursor);- const stored: Stored = {- rows: rows ?? [],- cursor: cursors.current.get(storageKey(companyId, list.name)) ?? null- };+ // A broadcast's patch is not stored. It does not move the cursor, so the+ // next load asks the log from the same place and re-reads these rows+ // whether or not the stored copy had them; and storing means writing the+ // whole list (about 150 ms of blocked page for 150,000 items) per change.+ if (!cursor) return;+ cursors.current.set(storageKey(companyId, list.name), cursor);+ const stored: Stored = { rows: rows ?? [], cursor };// The stored copy only speeds up the next load.try {- await (await storage()).setItem(- storedKey(companyId, userId, list.name),- stored- );+ const idb = await storage();+ const key = storedKey(companyId, userId, list.name);+ await idb.setItem(key, stored);+ // An absolute instant, only ever compared with another one.+ await idb.setItem(storedAtKey(key), Date.now());} catch (error) {logger.warn("live list not stored", { list: list.name, error });}@@ -274,6 +302,28 @@ export function LiveLists({p_epoch: since?.epoch,p_at: since?.at});+ if (error?.code === NOT_A_MEMBER) {+ // The user left this company while the page was open: nothing of its+ // lists stays in memory or on the device.+ logger.warn("live lists dropped: no longer a member", { companyId });+ // Memory first, and without storage: a blocked or failing IndexedDB+ // must not leave the company's rows on the page.+ for (const list of lists) {+ queryClient.setQueryData(liveListKey(companyId, list.name), []);+ cursors.current.delete(storageKey(companyId, list.name));+ }+ try {+ const idb = await storage();+ await Promise.all(+ lists.map((list) =>+ forget(idb, storedKey(companyId, userId, list.name))+ )+ );+ } catch (error) {+ logger.warn("stored live lists not removed", { companyId, error });+ }+ return;+ }if (error) throw error;if (active.current !== companyId) return;const log = data as unknown as LoggedChanges;@@ -310,7 +360,45 @@ export function LiveLists({));},- [carbon, companyId, rowsOf, readIds, commit, inTurn]+ [+ carbon,+ companyId,+ userId,+ lists,+ storage,+ queryClient,+ rowsOf,+ readIds,+ commit,+ inTurn+ ]+ );++ /** Remove the stored lists that are too old, another user's, or a company's the user has left. */+ const prune = useCallback(+ async (idb: LiveListStorage) => {+ const names = lists.map((list) => list.name);+ const keys = await idb.keys();+ const stale = staleStoredKeys(keys, {+ names,+ userId,+ companyIds: [companyId, ...memberOf.current]+ });+ const kept = storedListKeys(keys, names).filter(+ (key) => !stale.includes(key)+ );+ const expired = expiredStoredKeys(+ await Promise.all(+ kept.map(+ async (key) =>+ [key, await idb.getItem(storedAtKey(key))] as [string, unknown]+ )+ ),+ Date.now()+ );+ await Promise.all([...stale, ...expired].map((key) => forget(idb, key)));+ },+ [lists, userId, companyId]);// Cold load: IndexedDB first so pickers have options at once, then the log.@@ -320,6 +408,7 @@ export function LiveLists({// Without storage (blocked, or no driver) the lists come from the server.try {const idb = await storage();+ await prune(idb);await Promise.all(lists.map(async (list) => {const stored = readStored(@@ -345,7 +434,39 @@ export function LiveLists({return () => {cancelled = true;};- }, [companyId, userId, ready, lists, storage, queryClient, rowsOf, sync]);+ }, [+ companyId,+ userId,+ ready,+ lists,+ storage,+ queryClient,+ rowsOf,+ sync,+ prune+ ]);++ // While the page stays open: a stored list still goes when it is a day old+ // or stops being this user's, and the log is asked again, which also notices+ // a user who has left the company. A hidden tab only tidies the device.+ useEffect(() => {+ if (!ready) return;+ const timer = setInterval(() => {+ (async () => {+ // Tidying the device is best-effort; the sync below is what notices+ // a user who has left the company, and must run without it.+ try {+ await prune(await storage());+ } catch (error) {+ logger.warn("stored live lists not pruned", { error });+ }+ if (document.visibilityState === "visible") await sync(lists);+ })().catch((error) =>+ logger.warn("live list background check failed", { error })+ );+ }, BACKGROUND_CHECK_MS);+ return () => clearInterval(timer);+ }, [ready, lists, storage, sync, prune]);// Every (list, table) pair has its own topic, and so its own channel.const topicCount = lists.reduce(