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
feat: rewrite user select for lazy, paginated, cached group loading (#1143)
Brad Barbin7fc6a1f9a7c7
diff --git a/.ai/plans/2026-07-14-user-select-rewrite.md b/.ai/plans/2026-07-14-user-select-rewrite.mdnew file mode 100644index 0000000000..4613525ac1--- /dev/null+++ b/.ai/plans/2026-07-14-user-select-rewrite.md@@ -0,0 +1,800 @@+# User Select Performance Rewrite — implementation plan++**Spec:** .ai/specs/2026-07-14-user-select-rewrite.md+**Research:** N/A — skipped with rationale documented in the spec (frontend data-fetching pattern, not ERP-domain)+**Branch:** featuser-select++Global constraints for every task:++- **Types (amended 2026-07-14, user directive):** the local stack is running for this build — apply the migration with `pnpm db:migrate` (regenerates types from the local DB). Then inspect `git diff --stat packages/database/src/types.ts`: if the diff is clean (only the two new RPC signatures plus trivial churn), COMMIT it with Task 1 and use properly typed `client.rpc(...)` calls in Task 2 (no casts). If it contains large unrelated churn (per-company tables etc.), discard it (`git checkout -- packages/database/src/types.ts`) and fall back to `// @ts-ignore` + result casts (precedent: `apps/erp/app/modules/people/people.service.ts:312`, `documents.service.ts:178`).+- Never run a whole-repo typecheck. Scoped: `pnpm exec turbo run typecheck --filter=erp`.+- New user-visible strings in `TreeSelect.tsx` stay plain English (matching that file's existing untranslated strings: "No options found", "Group", "members"). Do not add Lingui macros to it in this PR — `SelectionList.tsx` keeps its existing Lingui usage.+- Counts render as plain numbers — never wrap a count in parentheses.++## Progress++- [x] Task 1: Create the user-select RPC migration (commit 7c3dfa54d — applied by stack boot; types regen kept: clean diff + new RPCs)+- [x] Task 2: Add user-select service functions and types to the users module (commit 7caabce5c — typed rpc calls; pre-commit codegen added MCP tool-metadata entries)+- [x] Task 3: Add query-key factories, cachedApiQuery, and invalidateUserSelectQueries (commit e8932e748)+- [x] Task 4: Create the five API routes and path helpers (commit 01fe515a5 — includes lesson-prescribed @ts-ignore conversion on two supplierPart delete routes)+- [x] Task 5: Rewrite UserSelect internals (hook, tree, focus, chips) (commit 34a4af4d3)+- [x] Task 6: Migrate EmailRecipients off the eager endpoint (commit 8105266b1)+- [x] Task 7: Wire cache invalidation into all group-mutating routes (commit 3c5a91ff4 — 11 routes)+- [x] Task 8: Delete the old endpoints, path helpers, and query key (commit a5b69a066 — Group type + arrayToTree kept: admin groups.tsx uses them)+- [x] Task 9: Run validation gates (typecheck ✓, lint ✓ — 13 warnings all in pre-existing untouched files, tests 21/21 tasks ✓, generated types clean)+- [x] Task 10: Browser-verify via /test (10/11 scenarios PASS; EmailRecipients modal flow SKIP — empty dev DB, its unique endpoint smoke-tested live; two fixes landed: explode ghost chip + sentinel root, commit 17a655389; screenshots in .ai/scratch/e2e/; playbook .ai/playbooks/user-select.md)++## Dependencies++- Task 2 needs Task 1 (RPC names/signatures). Task 3 is independent of Tasks 1–2 (can run in parallel).+- Task 4 needs Tasks 2 + 3. Tasks 5, 6, 7 need Tasks 3 + 4 and are independent of each other (parallelizable).+- Task 8 needs Tasks 5 + 6 (all consumers migrated). Task 9 needs Tasks 1–8. Task 10 needs Task 9.++---++## Task 1: Create the user-select RPC migration++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/<generated-timestamp>_user-select-rpcs.sql`++**Steps:**++1. From the repo root run `pnpm db:migrate:new user-select-rpcs`. Use the file it creates (never hand-pick the timestamp; if the generated filename ends in `000000`, delete it and rerun until the HHMMSS portion is not `000000`).+2. Paste exactly this SQL into the new file:++```sql+-- User-select rewrite: purpose-built, non-recursive, company-scoped group reads.+-- Replaces the recursive "groups" view on the user-select hot path.+-- SECURITY INVOKER: membership/user RLS applies to the caller.+-- plpgsql (not LANGUAGE sql) so the internal ORDER BY survives PostgREST.++CREATE OR REPLACE FUNCTION get_user_select_groups(+ p_company_id TEXT,+ p_type TEXT DEFAULT NULL,+ p_search TEXT DEFAULT NULL,+ p_limit INT DEFAULT 25,+ p_offset INT DEFAULT 0+) RETURNS TABLE (+ "id" TEXT,+ "name" TEXT,+ "isEmployeeTypeGroup" BOOLEAN,+ "isCustomerOrgGroup" BOOLEAN,+ "isCustomerTypeGroup" BOOLEAN,+ "isSupplierOrgGroup" BOOLEAN,+ "isSupplierTypeGroup" BOOLEAN,+ "userCount" INT,+ "groupCount" INT,+ "isRoot" BOOLEAN+) LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ -- Deterministic per-company root group ids. Must match the expressions in+ -- 20230123004632_groups.sql (create_employee_type_group / create_customer_type_group /+ -- create_supplier_type_group triggers).+ _roots TEXT[] := ARRAY[+ '00000000-0000-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12),+ '11111111-1111-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12),+ '22222222-2222-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12)+ ];+BEGIN+ RETURN QUERY+ SELECT+ g."id",+ g."name",+ g."isEmployeeTypeGroup",+ g."isCustomerOrgGroup",+ g."isCustomerTypeGroup",+ g."isSupplierOrgGroup",+ g."isSupplierTypeGroup",+ (SELECT count(*)::INT FROM "membership" m+ JOIN "user" u ON u."id" = m."memberUserId"+ WHERE m."groupId" = g."id" AND u."active" = TRUE) AS "userCount",+ (SELECT count(*)::INT FROM "membership" m+ WHERE m."groupId" = g."id" AND m."memberGroupId" IS NOT NULL) AS "groupCount",+ (g."id" = ANY(_roots)) AS "isRoot"+ FROM "group" g+ WHERE g."companyId" = p_company_id+ AND g."isIdentityGroup" = FALSE+ AND CASE+ WHEN p_type = 'employee' THEN NOT (+ g."isCustomerOrgGroup" OR g."isCustomerTypeGroup"+ OR g."isSupplierOrgGroup" OR g."isSupplierTypeGroup")+ WHEN p_type = 'customer' THEN (g."isCustomerTypeGroup" OR g."isCustomerOrgGroup")+ WHEN p_type = 'supplier' THEN (g."isSupplierTypeGroup" OR g."isSupplierOrgGroup")+ ELSE TRUE+ END+ AND CASE+ WHEN p_search IS NOT NULL AND p_search <> ''+ -- search mode: any depth, flat+ THEN g."name" ILIKE '%' || p_search || '%'+ -- browse mode: top-level only (roots, children of roots, parentless groups)+ ELSE (+ g."id" = ANY(_roots)+ OR EXISTS (SELECT 1 FROM "membership" m+ WHERE m."memberGroupId" = g."id" AND m."groupId" = ANY(_roots))+ OR NOT EXISTS (SELECT 1 FROM "membership" m WHERE m."memberGroupId" = g."id")+ )+ END+ ORDER BY+ (g."id" = ANY(_roots)) DESC,+ (g."isEmployeeTypeGroup" OR g."isCustomerTypeGroup" OR g."isSupplierTypeGroup") DESC,+ g."name" ASC,+ g."id" ASC+ LIMIT p_limit OFFSET p_offset;+END;+$$;++-- Direct members of one group: child groups (with counts) + direct active users.+CREATE OR REPLACE FUNCTION get_user_select_group_members(+ p_company_id TEXT,+ p_group_id TEXT+) RETURNS JSONB LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ _result JSONB;+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM "group" g+ WHERE g."id" = p_group_id AND g."companyId" = p_company_id+ ) THEN+ RETURN jsonb_build_object('groups', '[]'::jsonb, 'users', '[]'::jsonb);+ END IF;++ SELECT jsonb_build_object(+ 'groups', COALESCE((+ SELECT jsonb_agg(jsonb_build_object(+ 'id', cg."id",+ 'name', cg."name",+ 'isEmployeeTypeGroup', cg."isEmployeeTypeGroup",+ 'isCustomerOrgGroup', cg."isCustomerOrgGroup",+ 'isCustomerTypeGroup', cg."isCustomerTypeGroup",+ 'isSupplierOrgGroup', cg."isSupplierOrgGroup",+ 'isSupplierTypeGroup', cg."isSupplierTypeGroup",+ 'userCount', (SELECT count(*)::INT FROM "membership" m2+ JOIN "user" u2 ON u2."id" = m2."memberUserId"+ WHERE m2."groupId" = cg."id" AND u2."active" = TRUE),+ 'groupCount', (SELECT count(*)::INT FROM "membership" m3+ WHERE m3."groupId" = cg."id" AND m3."memberGroupId" IS NOT NULL)+ ) ORDER BY cg."name" ASC, cg."id" ASC)+ FROM "membership" m+ JOIN "group" cg ON cg."id" = m."memberGroupId"+ WHERE m."groupId" = p_group_id+ AND m."memberGroupId" IS NOT NULL+ AND cg."isIdentityGroup" = FALSE+ ), '[]'::jsonb),+ 'users', COALESCE((+ SELECT jsonb_agg(jsonb_build_object(+ 'id', u."id",+ 'firstName', u."firstName",+ 'lastName', u."lastName",+ 'fullName', u."fullName",+ 'email', u."email",+ 'avatarUrl', u."avatarUrl"+ ) ORDER BY u."lastName" ASC, u."firstName" ASC, u."id" ASC)+ FROM "membership" m+ JOIN "user" u ON u."id" = m."memberUserId"+ WHERE m."groupId" = p_group_id+ AND m."memberUserId" IS NOT NULL+ AND u."active" = TRUE+ ), '[]'::jsonb)+ ) INTO _result;++ RETURN _result;+END;+$$;++NOTIFY pgrst, 'reload schema';+```++3. Validate in a rolled-back transaction BEFORE applying (uses the worktree DB port from `.env.local`):++```bash+DB_PORT=$(grep -E "^PORT_DB=" .env.local | cut -d= -f2)+MIGRATION=$(ls -t packages/database/supabase/migrations/*_user-select-rpcs.sql | head -1)+PGPASSWORD=postgres psql -h 127.0.0.1 -p "$DB_PORT" -U postgres -d postgres -v ON_ERROR_STOP=1 <<SQL+BEGIN;+\i $MIGRATION+DO \$\$+DECLARE+ _company TEXT;+ _n INT;+ _members JSONB;+BEGIN+ SELECT "id" INTO _company FROM "company" LIMIT 1;+ IF _company IS NULL THEN RAISE EXCEPTION 'no seeded company found'; END IF;++ SELECT count(*) INTO _n FROM get_user_select_groups(_company, 'employee', NULL, 25, 0);+ IF _n = 0 THEN RAISE EXCEPTION 'expected at least one top-level employee group'; END IF;++ IF NOT EXISTS (+ SELECT 1 FROM get_user_select_groups(_company, 'employee', NULL, 25, 0) WHERE "isRoot"+ ) THEN RAISE EXCEPTION 'expected All Employees root pinned in first page'; END IF;++ SELECT get_user_select_group_members(_company, (+ SELECT "id" FROM get_user_select_groups(_company, 'employee', NULL, 25, 0)+ WHERE NOT "isRoot" LIMIT 1+ )) INTO _members;+ IF _members->'users' IS NULL OR _members->'groups' IS NULL+ THEN RAISE EXCEPTION 'members payload missing keys'; END IF;++ -- cross-company guard+ SELECT get_user_select_group_members('zzzznotacompanyzzzz', (+ SELECT "id" FROM "group" WHERE "companyId" = _company LIMIT 1+ )) INTO _members;+ IF jsonb_array_length(_members->'users') <> 0 OR jsonb_array_length(_members->'groups') <> 0+ THEN RAISE EXCEPTION 'cross-company members leak'; END IF;++ RAISE NOTICE 'user-select RPC assertions passed';+END+\$\$;+ROLLBACK;+SQL+```++4. Apply locally WITH type regeneration: `pnpm db:migrate`. Then inspect the generated-types diff per the amended global constraint (clean → keep and commit; unrelated churn → discard and use casts in Task 2).++**Verify:**+```bash+# (validation script above)+# Expected: NOTICE: user-select RPC assertions passed, then ROLLBACK+pnpm db:migrate+# Expected: the new migration applies with no error; types regenerate+git diff --stat packages/database/src/types.ts+# Expected: a small diff adding get_user_select_groups + get_user_select_group_members+# (if instead it shows large unrelated churn: git checkout -- packages/database/src/types.ts and use the cast fallback in Task 2)+```++**Out of scope:** Do NOT modify the `groups` / `groups_recursive` / `groupMembers` views, `groups_query`, `groups_for_user`, `users_for_groups`, or any table/RLS. Do not add RLS to `group` (Ask First territory, deliberately deferred).++---++## Task 2: Add user-select service functions and types to the users module++**Depends on:** Task 1+**Files:**+- Modify: `apps/erp/app/modules/users/types.ts` — add `UserSelectGroup`, `UserSelectGroupMembers`+- Modify: `apps/erp/app/modules/users/users.service.ts` — add four functions near `getGroupEmails` (~line 249)+- Copy from (precedent): `apps/erp/app/modules/users/users.service.ts:229-262` (`getGroups` for RPC-call shape, `getGroupEmails` for the cast pattern); `apps/erp/app/modules/users/users.service.ts:274-299` (`getSuppliers` for the `!inner` embed + filter)++**Steps:**++1. In `types.ts` add (keep the existing `Group` and `User` types untouched for now — `Group` is removed in Task 8 if orphaned):++```typescript+export type UserSelectGroup = {+ id: string;+ name: string;+ isEmployeeTypeGroup: boolean;+ isCustomerOrgGroup: boolean;+ isCustomerTypeGroup: boolean;+ isSupplierOrgGroup: boolean;+ isSupplierTypeGroup: boolean;+ userCount: number;+ groupCount: number;+ isRoot?: boolean; // present on list results, absent on member child groups+};++export type UserSelectGroupMembers = {+ groups: UserSelectGroup[];+ users: User[];+};+```++2. In `users.service.ts` add four functions. If Task 1 committed regenerated types, call the RPCs directly typed (drop the `// @ts-ignore` lines and the `as unknown as Promise<...>` casts below — but KEEP explicit return-shape types on the functions so downstream code doesn't depend on generated Json shapes for the JSONB result). If Task 1 fell back, use the casts exactly as written:++```typescript+export async function getUserSelectGroups(+ client: SupabaseClient<Database>,+ companyId: string,+ args: { type?: string; search?: string; limit: number; offset: number }+) {+ // @ts-ignore — RPC added in <timestamp>_user-select-rpcs.sql; not in cloud-generated types+ return client.rpc("get_user_select_groups", {+ p_company_id: companyId,+ p_type: args.type ?? null,+ p_search: args.search ?? null,+ p_limit: args.limit,+ p_offset: args.offset+ }) as unknown as Promise<{ data: UserSelectGroup[] | null; error: PostgrestError | null }>;+}++export async function getUserSelectGroupMembers(+ client: SupabaseClient<Database>,+ companyId: string,+ groupId: string+) {+ // @ts-ignore — RPC added in <timestamp>_user-select-rpcs.sql; not in cloud-generated types+ return client.rpc("get_user_select_group_members", {+ p_company_id: companyId,+ p_group_id: groupId+ }) as unknown as Promise<{ data: UserSelectGroupMembers | null; error: PostgrestError | null }>;+}++export async function searchUsersForSelect(+ client: SupabaseClient<Database>,+ companyId: string,+ args: { q: string; excludeSelf?: string | null; allowedIds?: string[]; userId: string }+) {+ const query = client+ .from("user")+ .select(+ "id, firstName, lastName, fullName, email, avatarUrl, userToCompany!inner(companyId)"+ )+ .eq("userToCompany.companyId", companyId)+ .eq("active", true)+ .ilike("fullName", `%${args.q}%`)+ .order("lastName")+ .limit(20);++ if (args.excludeSelf === "true") query.neq("id", args.userId);+ if (args.allowedIds && args.allowedIds.length > 0) query.in("id", args.allowedIds);++ return query;+}++export async function resolveUserSelectIds(+ client: SupabaseClient<Database>,+ companyId: string,+ ids: string[]+) {+ const [users, groups] = await Promise.all([+ client+ .from("user")+ .select("id, firstName, lastName, fullName, email, avatarUrl")+ .in("id", ids),+ client+ .from("group")+ .select("id, name")+ .in("id", ids)+ .eq("companyId", companyId)+ .eq("isIdentityGroup", false)+ ]);+ return { users, groups };+}+```++Import `PostgrestError` from `@supabase/supabase-js` (type-only) if not already imported.++3. Confirm `apps/erp/app/modules/users/index.ts` re-exports `./types` and `./users.service` (it is a barrel — if the new names aren't picked up automatically, add them).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0 (no new type errors)+```++**Out of scope:** Do not modify `getGroups`, `getGroupMembers`, `getGroupEmails`, or `upsertGroupMembers`. Do not touch `users.models.ts` (no form changes).++**Escape hatch:** If the `userToCompany!inner(companyId)` embed fails at runtime with PGRST200 (relationship not found), STOP and report — do not silently drop the company scoping. (The FK `userToCompany.userId → user.id` exists in `20230123004116_users-and-companies.sql:42`, so this should resolve.)++---++## Task 3: Add query-key factories, cachedApiQuery, and invalidateUserSelectQueries++**Depends on:** none (parallel with Tasks 1–2)+**Files:**+- Modify: `apps/erp/app/utils/react-query.ts` — append factories + two helpers+- Copy from (precedent): same file, `groupsByTypeQuery` (lines 184-190) for factory shape; `getClientCache` (lines 22-28)++**Steps:**++1. Append to `apps/erp/app/utils/react-query.ts`:++```typescript+export const userSelectGroupsQuery = (+ companyId: string | null,+ type: string | null,+ offset: number+) => ({+ queryKey: ["userSelectGroups", companyId ?? "null", type ?? "all", offset],+ staleTime: RefreshRate.Low+});++export const userSelectMembersQuery = (+ companyId: string | null,+ groupId: string+) => ({+ queryKey: ["userSelectMembers", companyId ?? "null", groupId],+ staleTime: RefreshRate.Low+});++export const userSelectSearchQuery = (+ companyId: string | null,+ type: string | null,+ q: string,+ filters: string+) => ({+ queryKey: ["userSelectSearch", companyId ?? "null", type ?? "all", q, filters],+ staleTime: RefreshRate.High+});++export const userSelectResolveQuery = (+ companyId: string | null,+ ids: string[]+) => ({+ queryKey: ["userSelectResolve", companyId ?? "null", [...ids].sort().join(",")],+ staleTime: RefreshRate.Low+});++export const groupEmailsQuery = (companyId: string | null, groupId: string) => ({+ queryKey: ["groupEmails", companyId ?? "null", groupId],+ staleTime: RefreshRate.Low+});++const USER_SELECT_QUERY_PREFIXES = [+ "userSelectGroups",+ "userSelectMembers",+ "userSelectSearch",+ "userSelectResolve",+ "groupEmails"+];++/**+ * Read-through fetch against an API route, cached in window.clientCache.+ * fetchQuery dedupes concurrent identical calls and honors staleTime.+ * Falls back to a plain fetch when the cache isn't mounted yet.+ */+export async function cachedApiQuery<T>(+ query: { queryKey: unknown[]; staleTime: number },+ url: string+): Promise<T> {+ const queryFn = async (): Promise<T> => {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`Request failed with status ${res.status}`);+ return res.json();+ };+ const cache = getClientCache();+ if (!cache) return queryFn();+ return cache.fetchQuery({+ queryKey: query.queryKey,+ queryFn,+ staleTime: query.staleTime+ });+}++export function invalidateUserSelectQueries(companyId: string | null) {+ window.clientCache?.invalidateQueries({+ predicate: (query) => {+ const queryKey = query.queryKey as unknown[];+ return (+ USER_SELECT_QUERY_PREFIXES.includes(queryKey[0] as string) &&+ queryKey[1] === (companyId ?? "null")+ );+ }+ });+}+```++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** Do not modify existing factories or `RefreshRate`. Do not remove `groupsByTypeQuery` yet (Task 8).++---++## Task 4: Create the five API routes and path helpers++**Depends on:** Tasks 2, 3+**Files:**+- Create: `apps/erp/app/routes/api+/users.select.groups.tsx`+- Create: `apps/erp/app/routes/api+/users.select.groups.$groupId.members.tsx`+- Create: `apps/erp/app/routes/api+/users.select.search.tsx`+- Create: `apps/erp/app/routes/api+/users.select.resolve.tsx`+- Create: `apps/erp/app/routes/api+/users.select.groups.$groupId.emails.tsx`+- Modify: `apps/erp/app/utils/path.ts` — add five helpers in the `api` block next to `groupsByType` (line 62)+- Copy from (precedent): `apps/erp/app/routes/api+/users.search.tsx` (loader shape: `requirePermissions` role employee → parse params → service → `data({...}, flash)` on error → plain object on success)++**Steps:**++1. Path helpers (in the `api` block of `path.ts`; keep the old ones for now):++```typescript+userSelectGroups: (type: string | undefined, offset: number, limit = 25) =>+ generatePath(+ `${api}/users/select/groups?type=${type ?? ""}&offset=${offset}&limit=${limit}`+ ),+userSelectGroupMembers: (groupId: string) =>+ generatePath(`${api}/users/select/groups/${groupId}/members`),+userSelectSearch: (q: string, type?: string) =>+ generatePath(+ `${api}/users/select/search?q=${encodeURIComponent(q)}&type=${type ?? ""}`+ ),+userSelectResolve: (ids: string[]) =>+ generatePath(`${api}/users/select/resolve?ids=${ids.join(",")}`),+userSelectGroupEmails: (groupId: string) =>+ generatePath(`${api}/users/select/groups/${groupId}/emails`),+```++2. `users.select.groups.tsx` — full file:++```typescript+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getUserSelectGroups } from "~/modules/users";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ role: "employee"+ });++ const url = new URL(request.url);+ const type = url.searchParams.get("type") || undefined;+ const offset = Math.max(0, Number(url.searchParams.get("offset")) || 0);+ const limit = Math.min(+ 100,+ Math.max(1, Number(url.searchParams.get("limit")) || 25)+ );++ const result = await getUserSelectGroups(client, companyId, {+ type,+ limit: limit + 1, // fetch one extra row to compute hasMore+ offset+ });++ if (result.error) {+ return data(+ { groups: [], hasMore: false, error: result.error },+ await flash(request, error(result.error, "Failed to load groups"))+ );+ }++ const rows = result.data ?? [];+ return {+ groups: rows.slice(0, limit),+ hasMore: rows.length > limit+ };+}+```++3. `users.select.groups.$groupId.members.tsx` — same skeleton; read `params.groupId` (return `{ groups: [], users: [] }` with a 400-style flash if missing), call `getUserSelectGroupMembers(client, companyId, groupId)`, on success `return { groups: result.data?.groups ?? [], users: result.data?.users ?? [] }`.+4. `users.select.search.tsx` — same skeleton; params: `q` (trim; if missing or `< 2` chars return `{ groups: [], users: [] }`), `type`, `excludeSelf`, `allowedIds` (comma-split, filter Boolean). Run in parallel:+ - `getUserSelectGroups(client, companyId, { type, search: q, limit: 10, offset: 0 })`+ - `searchUsersForSelect(client, companyId, { q, excludeSelf, allowedIds, userId })` (destructure `userId` from `requirePermissions`)+ On either error, flash + return empty arrays. On success strip the embed from user rows: `users: (usersResult.data ?? []).map(({ userToCompany, ...u }) => u)` and return `{ groups: groupsResult.data ?? [], users }`.+5. `users.select.resolve.tsx` — same skeleton; param `ids` (comma-split, filter Boolean, dedupe, cap at 200; empty → `{ users: [], groups: [] }`), call `resolveUserSelectIds(client, companyId, ids)`; if either sub-result has an error, flash the first error and return empty arrays; else `return { users: users.data ?? [], groups: groups.data ?? [] }`.+6. `users.select.groups.$groupId.emails.tsx` — same skeleton; `getGroupEmails(client, [groupId])` (it returns `string[]`, not `{data,error}`); `return { emails: [...new Set(result)] }`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** No `clientLoader`s on these routes (caching lives solely in `cachedApiQuery` — a fetcher-less raw `fetch` never runs a clientLoader). Do not touch the four old routes yet.++---++## Task 5: Rewrite UserSelect internals (hook, tree, focus, chips)++**Depends on:** Tasks 3, 4+**Files:**+- Modify: `apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts` — data layer + handlers+- Modify: `apps/erp/app/components/Selectors/UserSelect/types.ts` — internal types+- Modify: `apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx` — recursive tree + interactions + sentinel+- Modify: `apps/erp/app/components/Selectors/UserSelect/components/Popover.tsx` — depth-N focus builder+- Modify: `apps/erp/app/components/Selectors/UserSelect/components/SelectionList.tsx` — `isGroup` usage only (via the helper change in the hook file)+- Copy from (precedent): `apps/erp/app/components/InfiniteScroll.tsx:47` for the `useInView` sentinel pattern (`react-intersection-observer` is already an erp dependency); keep the existing WAI-ARIA structure of `TreeSelect.tsx`/`Popover.tsx` as the baseline++**Steps:**++1. **types.ts (component)** — replace the data-shape types, keep `UserSelectProps`, `TreeNode`, refs untouched:+ - Import `UserSelectGroup`, `User` from `~/modules/users` (drop the `Group` import).+ - `SelectionGroupWithOptions` becomes `UserSelectGroup & { users: User[]; memberCount: number } & SelectionOptions` (the `users` key stays as the group discriminator — populated `[]` until exploded).+ - Add render-tree types:+ ```typescript+ export type UserOptionItem = User & SelectionOptions;+ export type GroupNode = {+ uid: string; // path-scoped: parentUid + "_" + groupId + "_group"+ group: UserSelectGroup;+ expanded: boolean;+ loading: boolean;+ members: { groups: GroupNode[]; users: UserOptionItem[] } | null; // null = not fetched+ };+ ```+ - `OptionGroup` is deleted; export a discriminated view model the tree renders:+ ```typescript+ export type UserSelectViewModel =+ | { mode: "browse"; nodes: GroupNode[]; hasMore: boolean; loadingMore: boolean }+ | { mode: "search"; groups: (UserSelectGroup & SelectionOptions)[]; users: UserOptionItem[]; searching: boolean };+ ```++2. **useUserSelect.ts** — replace the data layer; keep the public return-shape field names (`aria`, `selectionItemsById`, `dropdown`, `innerProps`, `refs`, all `on*` handlers) so `Input.tsx`, `Combobox.tsx`, `Container.tsx`, `provider.ts` need no changes:+ - Delete: `groupsFetcher` + its `useEffect`, `searchCache`, the `optionGroups` memo, `makeFilteredOptionGroups`, `filteredOptionGroups` state + its preserve-expansion effect, and the `usersBatch`/`group_`-prefix logic in the value-hydration effect.+ - New state: `topLevelGroups: UserSelectGroup[]`, `hasMore: boolean`, `loadingMore: boolean`, `initialLoading: boolean`, `membersById: Record<string, { groups: UserSelectGroup[]; users: User[] }>`, `loadingGroups` (keep), `expandedUids: Set<string>`, `search: { q: string; results: { groups: UserSelectGroup[]; users: User[] } | null; searching: boolean }`, `errors`.+ - All requests go through `cachedApiQuery` + the Task 3 factories + `getCompanyId()` (import both from `~/utils/react-query`). Company id may be `null` before hydration — factories tolerate it.+ - **Page loading:** on mount and on `type` change, reset pages and load offset 0 (`userSelectGroupsQuery(companyId, type ?? null, 0)` + `path.to.api.userSelectGroups(type, 0)`); `loadMore()` fetches the next offset (`topLevelGroups.length`) and appends, deduping by `id`. Set `errors` from a failed fetch (catch; store `{ message }`) — hook still returns `errors` and `loading` (map `loading` to `initialLoading`).+ - **prefetchGroup(groupId):** unchanged trigger points, new body — `cachedApiQuery(userSelectMembersQuery(companyId, groupId), path.to.api.userSelectGroupMembers(groupId))` → store raw response in `membersById`; keep `loadingGroups` bookkeeping. Apply `queryFilters.allowedIds` filtering to `users` at read time (NOT before caching — the cache entry must stay filter-agnostic).+ - **Expansion:** `onGroupExpand(uid)` adds to `expandedUids` + prefetches the node's groupId; `onGroupCollapse(uid)` removes. `uid` for a top-level node = `getGroupId(instanceId, group.id)`; for a nested node = `getOptionId(parentUid, group.id)` (existing helpers — path-scoped, so the same group under two parents expands independently).+ - **View model memo:** browse mode builds `GroupNode[]` recursively from `topLevelGroups` + `membersById` + `expandedUids` (children materialized only for expanded nodes; guard cycles by skipping a child whose `id` already appears in its own uid path). `usersOnly` drops groups with `userCount + groupCount === 0`. Search mode maps `search.results`.+ - **Search:** keep the 240 ms `debounce`. `q.trim().length >= 2` → `cachedApiQuery(userSelectSearchQuery(companyId, type ?? null, q, `${excludeSelf}|${allowedIds}`), url)` where `url` = `path.to.api.userSelectSearch(q, type)` plus `&excludeSelf=true` / `&allowedIds=...` exactly as the old code appended them; store in `search.results` (groups filtered client-side by `allowedIds`? No — `allowedIds` applies to users only, server-side, as today). `q.length === 1` → stay in browse mode and client-filter top-level nodes by `stringContainsTerm(group.name, q)` (keep the helper). Empty `q` → clear search state.+ - **Value hydration effect:** unknown `value` ids (not in `selectionItemsById`) → one `cachedApiQuery(userSelectResolveQuery(companyId, ids), path.to.api.userSelectResolve(ids))`; hydrate users as today; hydrate groups as `{ ...g, users: [], memberCount: 0, uid: getOptionId("preselected", g.id), label: g.name }`. Track requested ids in a ref so a resolve that legitimately returns nothing (deleted id) doesn't refetch in a loop. Remove the `group_` prefix special-case.+ - **onSelect for groups:** selection item = `{ ...group, users: [], memberCount: group.userCount + group.groupCount, uid, label: group.name }`.+ - **onExplode:** make internally async — if `membersById[item.id]` is missing, first `await` the members fetch (same call as prefetch), then explode into direct users + direct child groups (child groups become selection items with `users: []`), replacing the group selection as today.+ - **isGroup helper (exported):** change to presence-based: `export function isGroup(item: IndividualOrGroup) { return "users" in item; }` — group selection items always carry `users` (possibly `[]`); user items never do. This keeps `SelectionList.tsx` `canExpand` and `Users.tsx` `verbose` working, and makes empty groups expandable-on-explode.+ - **onKeyDown changes:** `Enter` — if the focused node is a group row and groups are selectable (`!usersOnly`), toggle-select it (do NOT require `hasParent`); if `usersOnly`, toggle expansion. `Space` — same toggle semantics for group rows. `ArrowRight`/`ArrowLeft` keep expand/collapse. User rows keep existing behavior. `hasChildren(uid)` now reads `focusableNodes.current[uid].expandable`.+ - Return additionally: `viewModel`, `hasMore`, `loadingMore`, `loadMore`, keeping every existing returned field name.++3. **Popover.tsx** — replace the two-level DOM walk (lines 25-77) with a depth-N walk so nesting works: query `listBoxRef.current.querySelectorAll('[role="treeitem"]')` in DOM order; for each element, `uid = el.id`, `expandable = el.getAttribute("data-expandable") === "true"`, `parentId` = the `id` of the nearest ancestor element with `role="treeitem"` (via `el.parentElement?.closest('[role="treeitem"]')`, `undefined` at top level); then build the same triple linked-list. Keep the effect deps (`[children, ...]`) so it rebuilds when the tree re-renders (expansion, new pages, search).+4. **TreeSelect.tsx** — rewrite rendering:+ - Browse mode: recursive `<GroupRow node={...} depth={n}>`. The row is `role="treeitem"`, `id={node.uid}`, `data-expandable={canExpand}`, and contains: a chevron **button** (`ExpandIcon` wrapped in a 40px-hit-area button; `onClick` stops propagation and toggles expand; hidden when `userCount + groupCount === 0`), the group name, the `userCount` as the plain-number badge (or `Spinner` while loading — keep current pattern), and the same check/selected treatment `Option` rows use. **Row `onClick` = toggle selection** when `!usersOnly` (respect `alwaysSelected` disable), else toggle expansion. `onMouseEnter` prefetches when collapsed (keep). Expanded content: nested `<ul role="group">` with child `GroupRow`s first, then user `Option` rows (reuse the existing `Option` component; drop its group-item branch usage in browse mode — groups render only as `GroupRow` now, so the duplicated "group as first item" disappears). Expanded-but-empty (members loaded, zero items): muted "No members" row.+ - After the last top-level node render the sentinel + load-more UI:+ ```tsx+ {viewModel.hasMore && <SentinelRow onVisible={loadMore} loading={viewModel.loadingMore} />}+ ```+ `SentinelRow` uses `useInView` from `react-intersection-observer` exactly like `apps/erp/app/components/InfiniteScroll.tsx:47` (`threshold: 0`, effect calls `onVisible()` when `inView && !loading`), rendering a `Spinner` row while loading. Give it NO `role`/`id` so the focus builder ignores it.+ - Search mode: two flat sections with plain non-interactive headers ("Groups" — hidden when `usersOnly` or empty; "People") whose rows are `Option`-style `role="treeitem"` items: group rows show `LuUsers` icon + name + "N members" (from `userCount`) + the "Group" badge, are selectable, and have NO chevron and `data-expandable="false"`; user rows unchanged. Keep "No options found" for zero results.+ - Loading: keep the existing top-level `Spinner` block for `initialLoading`.+5. **SelectionList.tsx** — no structural change; verify `canExpand` still works via the new `isGroup` (it will — group items keep `users`).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+pnpm run lint 2>&1 | tail -5+# Expected: no new errors in apps/erp/app/components/Selectors/UserSelect/**+```++**Out of scope:** `Input.tsx`, `Combobox.tsx`, `Container.tsx`, `provider.ts`, `UserSelect.tsx` stay untouched. Wrapper components (`Form/Users.tsx`, `Form/User.tsx`, `Form/Employees.tsx`, `Assignee.tsx`) and all call sites stay untouched — if any of them fails to compile against the new internals, STOP and report; do not change wrapper contracts.++**Escape hatch:** If the DOM-order focus walk conflicts with how `aria-activedescendant` focus currently behaves (keyboard nav visibly broken in Task 10), STOP and report with the failing interaction — do not silently drop keyboard support.++---++## Task 6: Migrate EmailRecipients off the eager endpoint++**Depends on:** Tasks 3, 4+**Files:**+- Modify: `apps/erp/app/components/Form/EmailRecipients.tsx` — replace `useEmailOptions` (lines 57-120) and `handleSelect` (lines 214-223)+- Copy from (precedent): keep this file's own cmdk structure; fetch pattern from Task 5's `cachedApiQuery` usage++**Steps:**++1. Replace `useEmailOptions(type)`:+ - Delete the `groupsFetcher` + `groupsByTypeWithUsers` load and the recursive `collectGroupEmails`/`processGroup` flattening.+ - On mount: `cachedApiQuery(userSelectGroupsQuery(companyId, type, 0), path.to.api.userSelectGroups(type, 0))` → keep groups with `userCount + groupCount > 0` as `GroupOption`s: `{ type: "group", id, name, emails: [], memberCount: userCount }`.+ - Track `inputValue` (lift it or pass it into the hook): when `inputValue.trim().length >= 2`, `cachedApiQuery(userSelectSearchQuery(companyId, type, q, ""), path.to.api.userSelectSearch(q, type))` → options become matched groups (same mapping) + matched users with an email: `{ type: "user", id, name: fullName, email }` (skip users with null email), deduped by email as today. For shorter input keep the existing client-side filter over the mounted group options.+2. `handleSelect` for groups becomes async: `const { emails } = await cachedApiQuery<{ emails: string[] }>(groupEmailsQuery(companyId, option.id), path.to.api.userSelectGroupEmails(option.id)); addEmails(emails);`. User selection and raw-email Enter entry stay unchanged.+3. Update the `GroupOption` member-count subtitle to render `memberCount` (direct active users) — plain number.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+grep -rn "groupsByTypeWithUsers" apps/erp/app --include="*.tsx" --include="*.ts" | grep -v "utils/path.ts"+# Expected: no output (no consumers left)+```++**Out of scope:** The component's props, hidden-input emission (`name[index]`), validation, and popover UX stay unchanged.++---++## Task 7: Wire cache invalidation into all group-mutating routes++**Depends on:** Task 3+**Files (all Modify, all in `apps/erp/app/routes/x+/users+/` unless noted):**+- `groups.new.tsx` — replace the existing predicate body (lines 75-84)+- `groups.$groupId.tsx` — add `clientAction` (none today)+- `groups.delete.$groupId.tsx` — add `clientAction` (none today)+- `employees.new.tsx` — replace the existing predicate (line ~130-137)+- `employees.$employeeId.tsx` — add `clientAction` (employee-type change moves memberships via DB trigger)+- `deactivate.tsx` — add `clientAction`+- `employee-types.new.tsx`, `employee-types.$employeeTypeId.tsx`, `employee-types.delete.$employeeTypeId.tsx` — add `clientAction` (triggers mirror employeeType rows into groups)+- `customers.new.tsx`, `suppliers.new.tsx` — add `clientAction` (interceptors create org groups)+- Copy from (precedent): `apps/erp/app/routes/x+/users+/groups.new.tsx:75-84` (existing clientAction shape)++**Steps:**++1. In each file add (or replace the body of) the `clientAction` with exactly:++```typescript+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+```++with imports `import type { ClientActionFunctionArgs } from "react-router";` and `import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";` (merge into existing imports where present).++2. In `groups.new.tsx` and `employees.new.tsx`, the existing `groupsByType` predicate is REPLACED by the helper call (the old key dies in Task 8) — do not keep both.++**Verify:**+```bash+grep -rln "invalidateUserSelectQueries" apps/erp/app/routes/x+/users+/ | wc -l+# Expected: 11+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** `bulk-edit-permissions.tsx`, invite routes (`resend-invite`, `revoke-invite`), and `operators.*` — they don't change groups or memberships.++---++## Task 8: Delete the old endpoints, path helpers, and query key++**Depends on:** Tasks 5, 6+**Files:**+- Delete: `apps/erp/app/routes/api+/users.groups.tsx`+- Delete: `apps/erp/app/routes/api+/users.groups.$groupId.members.tsx`+- Delete: `apps/erp/app/routes/api+/users.search.tsx`+- Delete: `apps/erp/app/routes/api+/users.batch.tsx`+- Modify: `apps/erp/app/utils/path.ts` — remove `groupsByType`, `groupsByTypeWithUsers`, `groupMembers`, `usersSearch`, `usersBatch` (lines 62-71)+- Modify: `apps/erp/app/utils/react-query.ts` — remove `groupsByTypeQuery` (lines 184-190)+- Modify: `apps/erp/app/modules/users/types.ts` — remove the tree `Group` type (lines 36-49) IF orphaned (see step 3)++**Steps:**++1. Delete the four route files and the five path helpers and `groupsByTypeQuery`.+2. `rg -n "groupsByType|groupsByTypeWithUsers|groupMembers\(|usersSearch|usersBatch|arrayToTree" apps/erp/app` — fix every remaining reference (there should be none after Tasks 5-7; if one appears outside the deleted files, STOP and report before deleting further).+3. `rg -n "Group\b" apps/erp/app/modules/users/ apps/erp/app/components/` for the tree `Group` type: if the only remaining importers were the deleted files / rewritten components, remove the type; if something else (e.g. admin Groups UI) imports it, leave it and note in the plan progress line.+4. Leave `performant-array-to-tree` in `package.json` if other code imports it; remove the import only from deleted files (they're deleted anyway). Run `rg -n "performant-array-to-tree" apps/erp` — if zero hits remain, remove it from `apps/erp/package.json` dependencies.++**Verify:**+```bash+rg -n "groupsByType|usersBatch|usersSearch|api/users/groups|api/users/batch|api/users/search" apps/erp/app+# Expected: no output+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0+```++**Out of scope:** DB views/RPCs (`groups`, `groups_recursive`, `groupMembers` view, `groups_query`, `groups_for_user`, `users_for_groups`) stay. Admin routes `x+/users+/groups.tsx` / `groups.$groupId.tsx` loaders (using `getGroups`/`getGroupMembers` service functions) stay.++---++## Task 9: Run validation gates++**Depends on:** Tasks 1–8+**Files:** none (verification only)++**Steps:**++1. `pnpm exec turbo run typecheck --filter=erp` — must exit 0.+2. `pnpm run lint` — must report no errors in changed files (pre-existing warnings elsewhere are acceptable).+3. `pnpm run test` — unit suite must pass (no unit tests cover UserSelect today; this guards regressions elsewhere).+4. Confirm generated types untouched: `git status --porcelain packages/database/src/types.ts` → empty.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp && pnpm run lint && pnpm run test+# Expected: all exit 0+```++**Out of scope:** No `pnpm run build` needed (no vite config/dependency changes). No whole-repo typecheck.++---++## Task 10: Browser-verify via /test++**Depends on:** Task 9+**Files:** none (verification; playbook may be cached to `.ai/playbooks/`)++**Steps:**++1. Ensure the dev stack is up (`crbn up`, plain portless mode). If it cannot boot, STOP — the task is blocked, not done.+2. Invoke the `/test` skill with this scenario list (it handles `/auth` login):+ - **Lazy first page:** Open Settings → Approvals → an approval rule form (`ApprovalRuleForm` renders `<Users type="employee">`). Open the select; confirm the list shows top-level groups with "All Employees" pinned first with a member-count badge, and via the browser network log confirm exactly one request to `/api/users/select/groups?...offset=0` and NO request to `/api/users/groups`.+ - **Click-to-select + chevron:** Click a group row → it becomes selected (chip appears) without expanding. Click its chevron → it expands showing users (and nested groups, if any) without changing selection. Expand a nested group if present.+ - **Hover prefetch + cache:** Collapse, re-expand the same group → no second members request (network log).+ - **Infinite scroll:** If the dev company has ≤25 top-level employee groups, create enough groups via Settings → Users → Groups (or psql fixtures) to exceed 25, reload, open the select, scroll the dropdown to the bottom → a second page request fires and more groups render.+ - **Search:** Type 1 character → list filters client-side, no search request. Type ≥2 chars (e.g. "eng") → one debounced `/api/users/select/search` request; flat Groups + People sections; group rows have no chevron; selecting a group from search works; clearing the input restores the browse list without a new page-0 request.+ - **Preselected resolve:** Open an existing record whose form has saved user+group selections (e.g. the same approval rule after saving, or Documents → share form) → chips render names immediately with a single `/api/users/select/resolve` request.+ - **Invalidation:** Rename a group in Settings → Users → Groups, return to the approval form, open the select → the renamed group shows (fresh `/api/users/select/groups` request after invalidation).+ - **usersOnly:** Open a `<Employees>` usage (Settings → Users → Employees → Bulk Edit Permissions) → group rows expand on click and are NOT selectable; only people can be selected.+ - **Explode:** In a multi select, select a group, click the chip's Expand button → the group is replaced by its direct members.+ - **EmailRecipients:** Open a flow using `EmailRecipients` (e.g. quote/order email dialog) → no `include=users` request; typing ≥2 chars searches; selecting a group adds its member emails; typing a raw email + Enter still adds it.+ - **GroupsForm verbose:** Settings → Users → Groups → edit a group's members → save → members persist (verbose `group_`/`user_` prefixes still round-trip).+3. Capture screenshots of the open select (browse mode with counts, search mode flat list) for the PR.++**Verify:**+```bash+# /test run report+# Expected: every scenario above passes; screenshots saved; any failure loops back to the offending task+```++**Out of scope:** No performance load-testing; the structural guarantees (bounded payload, no recursive view) are verified by the network assertions above.diff --git a/.ai/playbooks/user-select.md b/.ai/playbooks/user-select.mdnew file mode 100644index 0000000000..4ec0189088--- /dev/null+++ b/.ai/playbooks/user-select.md@@ -0,0 +1,48 @@+# User Select (groups + people picker)++Last tested: 2026-07-14+Route: any form with a `<Users>`/`<UserSelect>` field — easiest: /x/settings/approval-rules/new?type=purchaseOrder ("Who Can Approve"), /x/users/groups/new (GroupsForm, verbose mode), bulk Edit Permissions from /x/users/employees (usersOnly mode).++## Prerequisites++- Logged in via /auth ([email protected]).+- Seeded dev company has 2 employee groups (All Employees root + Admin). For pagination tests insert >25 parentless groups via psql (`INSERT INTO "group" ("name","companyId") SELECT 'Perf Test Group '||lpad(n::text,2,'0'), (SELECT id FROM company LIMIT 1) FROM generate_series(1,30) n;`) and DELETE them after. Raw-SQL fixtures do NOT invalidate the client cache — hard-reload the page to see them.++## Steps++### 1. Network assertions — patch fetch, don't use performance entries+Vite dev floods the resource-timing buffer (250 cap) before API fetches happen. Install:+`window.__apiLog=[]; window.__origFetch=window.fetch; window.fetch=(...a)=>{const u=String(a[0]); if(u.includes('/api/')) window.__apiLog.push(u); return window.__origFetch(...a)}`+The patch dies on full navigations (agent-browser open, some form submits) — reinstall after each.++### 2. Interacting with the select — use eval clicks, not @refs+The dropdown is an absolutely-positioned popover; a11y refs go stale across its re-renders and misclicks land on the drawer overlay (closing it). Reliable selectors:+- Input: `document.querySelector('[aria-haspopup=tree]')` → `.focus()` opens the dropdown and triggers page-0 fetch (`/api/users/select/groups?type=…&offset=0&limit=25`).+- Group rows: `[role=treeitem][data-expandable]`; row click = select (non-usersOnly) / expand (usersOnly). Header div is `:scope > div`.+- Chevron: `button[aria-label="Expand group"|"Collapse group"]` inside the row — expands without selecting; hover on a collapsed row prefetches members.+- Chips list: labels via `[...document.querySelectorAll('ul li p')].map(p=>p.textContent)`; buttons `aria-label="Expand <name>"` (explode) / `"Remove <name>"`.+- Wrapper form value: hidden inputs `input[name^="<fieldName>"]` (GroupsForm uses `selections[n]` with `user_`/`group_` prefixes).++### 3. Search+Type ≥2 chars with real key events (`keyboard type`) — synthetic `fill` doesn't always reach React state. One debounced `/api/users/select/search?q=…` request; flat Groups → People sections, group rows have the GROUP badge and no chevron. 1 char filters loaded pages client-side (no request). Clear via `button[aria-label="Clear search query"]`.++### 4. Approval rule save gotcha+`lowerBoundAmount` validator is `.gt(0)` and the currency field commits "0" — fill the visible amount input then blur (click another field), verify `input[name=lowerBoundAmount]` value, then `form.requestSubmit(createRuleButton)`. Also `/new` needs `?type=purchaseOrder` (documentType comes from the query param).++### 5. Verify+- Selection: chip appears; group row gets `aria-selected=true` without `aria-expanded` changing.+- Resolve: reopening a saved record fires ONE `/api/users/select/resolve?ids=…` and chips render with the dropdown closed.+- Invalidation: after group create/rename via the UI, the next select mount fires a FRESH page-0 request (no request = cache hit = invalidation broken).+- Infinite scroll: `tree.scrollTop = tree.scrollHeight` on `[role=tree]` → `offset=25` request; sentinel div (`justify-center` last child) disappears when hasMore=false.+- Group emails endpoint: `/api/users/select/groups/<id>/emails` → `{emails:[…]}`; foreign/unknown id → `{emails:[]}` (tenant guard).++## Selector Notes++- Bulk Edit Permissions: /x/users/employees → check a row checkbox → a count button ("1") appears top-left of the table → menu → "Edit Permissions" (the row-level Action Menu "Edit Permissions" opens the SINGLE-user page, not the usersOnly bulk form).+- Groups list has no "New Group" text button visible in a11y snapshots; navigate to /x/users/groups/new directly. Row edit links are `"<name> Open"`.++## Common Failures++- Clicks near the open dropdown hitting the drawer overlay → drawer closes, DOM queries return empty (looks like state was wiped). Always eval-click within the popover.+- `fill` on the select input with the same/empty value fires no React change — use `keyboard type` or the Clear button.+- Screenshots: agent-browser saves to ~/.agent-browser/tmp/screenshots/ regardless of the path arg — copy the newest file out.diff --git a/.ai/rules/clientAction-patterns.md b/.ai/rules/clientAction-patterns.mdindex ac06132c3c..3debb949df 100644--- a/.ai/rules/clientAction-patterns.md+++ b/.ai/rules/clientAction-patterns.md@@ -72,9 +72,15 @@ clientLoader.hydrate = true;- `clientLoader.hydrate = true` makes the client loader run on **initial hydration**, notjust subsequent client navigations — so the cache warms on first load. Present on all`api+` clientLoader files; no `HydrateFallback` is exported anywhere.-- Variants destructure `request` to fold URL search params into the key- (`apps/erp/app/routes/api+/users.groups.tsx` →- `groupsByTypeQuery(companyId, type)`).+- Variants fold route/search params into the key+ (`apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts` →+ `materialTypesQuery(substanceId, formId, companyId)`).+- For component-driven (non-navigation) fetches, `clientLoader` never runs — raw+ `fetch` bypasses it. Those use `cachedApiQuery(queryDef, url)`+ (`apps/erp/app/utils/react-query.ts`), an imperative+ `clientCache.fetchQuery` read-through with the same key factories, so+ `clientAction` invalidation still applies (see the user-select endpoints,+ invalidated by `invalidateUserSelectQueries`).## clientAction — cache invalidation (mutation routes, `x+/`)diff --git a/.ai/specs/2026-07-14-conductor-crbn-worktree-parity.md b/.ai/specs/2026-07-14-conductor-crbn-worktree-parity.mdnew file mode 100644index 0000000000..887c9b7388--- /dev/null+++ b/.ai/specs/2026-07-14-conductor-crbn-worktree-parity.md@@ -0,0 +1,410 @@+# Spec: Conductor ⇄ crbn worktree parity++**Status:** Implemented on branch — settings.toml activates once merged to `origin/main`+**Date:** 2026-07-14+**Author:** research + draft (agent)+**Area:** `packages/dev` (crbn CLI) + Conductor repo config+**Related rules:** `.ai/rules/environment-configuration.md`, `.ai/rules/dev-shared-redis.md`, `packages/dev/AGENTS.md`++## Changelog++- **2026-07-14 — implemented.** `crbn init` (`packages/dev/src/commands/init.ts`,+ `canonicalSlug` in `worktree.ts`); `crbn new`'s `.env`-copy task and the bash+ `checkout` `do_post_create` hook both now delegate to it; `crbn down --purge`+ (§9-C decision below); `conductor.json` → `.conductor/settings.toml`. Unit+ tests for `canonicalSlug` in `worktree.test.ts`. Verified: `pnpm --filter+ @carbon/dev typecheck` + `test` (38 pass) + a live `crbn init` run producing+ slug `carbon-featuser-select` (no longer collides with the main checkout's+ `carbon`).+- **§9-C resolved as `crbn down --purge`, not the recommended `crbn remove+ --path/--yes`.** Reason discovered in implementation: Conductor runs `archive`+ *inside* the workspace dir and manages worktree/dir removal itself, but `crbn+ remove` deliberately skips the *current* worktree and does its own `git+ worktree remove` — wrong fit. `down --purge` tears down the stack + volumes,+ flushes the redis db, and calls `removeSlot` (freeing the registry slot)+ without removing the dir, which is exactly what the archive hook needs.++---++## 1. Problem++`crbn new` / `crbn checkout` create a Carbon worktree whose dev environment is+fully isolated per-worktree: its own Docker Compose stack, ports, Supabase+JWT/anon/service keys, Redis logical DB, and portless `*.dev` domain. When we+instead create a workspace **inside Conductor**, Conductor does its own+`git worktree add` at `~/conductor/workspaces/<project>/<codename>` and then runs+a repo-level setup script. That script tries to bolt crbn's provisioning on top,+but it does so unreliably — the result is **not** equivalent to a `crbn checkout`+worktree, and in at least one real case it **collides with the main checkout**.++We want: **creating a workspace in Conductor produces the same fully-provisioned,+collision-free, branch-aligned worktree that `crbn new` / `crbn checkout` would —+even though the physical path differs.**++### 1.1 Evidence (current state on this machine)++`git worktree list` (abridged):++```+/Users/barbinbrad/Code/carbon [main] slug: carbon+/Users/barbinbrad/conductor/workspaces/carbon/moscow [featuser-select]+/Users/barbinbrad/conductor/workspaces/carbon/macau [fixquote-markup-aggressiveness]+```++`~/.carbon/dev-ports.json` (the slot registry, keyed by slug):++```+slug=carbon -> /Users/barbinbrad/conductor/workspaces/carbon/moscow PORT_ERP=54943+slug=macau -> /Users/barbinbrad/conductor/workspaces/carbon/macau PORT_ERP=57199+slug=carbon-feat-service -> /Users/barbinbrad/Code/carbon-feat-service (native crbn worktree)+```++- `~/Code/carbon/.carbon-worktree` = `carbon` (main checkout's slug).+- `moscow/.carbon-worktree` = **`carbon`** → **same slug as the main checkout.**+ Docker project `carbon-carbon` and the `carbon` registry key are shared between+ main and this Conductor workspace. Whichever boots second either hits+ `ensureSlugAvailable`'s "Slug already in use" error+ (`packages/dev/src/worktree.ts:95-120`) or steals the registry entry and+ re-allocates ports.+- `macau/.carbon-worktree` = `macau` → happens to be unique, so macau works.++The mechanism that produced both values is the same line in `conductor.json`+(`echo "$CONDUCTOR_WORKSPACE_NAME" > .carbon-worktree`), yet it yielded `carbon`+for one workspace and `macau` for another. **`$CONDUCTOR_WORKSPACE_NAME` is not a+reliable, unique, branch-aligned slug** (the first workspace of a project appears+to inherit the project name `carbon`). That is the root cause.++---++## 2. How it works today (grounded)++### 2.1 crbn: directory creation vs. environment provisioning are separate++- **`crbn new`** (`packages/dev/src/commands/new.ts`): `git worktree add -b <branch>`+ at a **sibling** of the main checkout, `"<repoBase>-<slugify(branch)>"`+ (`new.ts:38`), then copies `.env`. It does **not** allocate ports, mint JWTs,+ or write `.env.local`.+- **`crbn checkout`** (bash, `packages/dev/bin/crbn:173-296`): resolves/creates the+ worktree at the same `"<repoBase>-<slug>"` path, then runs `do_post_create`+ (`bin/crbn:404-417`) = `crbn env sync` + `.ai/scripts/install-skills.sh`. Also+ does **not** allocate ports or write `.env.local`.+- **`crbn up`** (`packages/dev/src/commands/up.ts`) is where the per-worktree+ environment is actually minted: `provisionSlot` → `resolveSlug` →+ `resolveSlot` (ports/redisDb/jwt, persisted to `~/.carbon/dev-ports.json`) →+ `branchToPrefix` → `renderEnv` → `writeEnv(.env.local)` (`up.ts:168-360`,+ `env.ts:6-113`).++So "do what `crbn checkout` does" = **(a)** the worktree exists (Conductor already+does this), **(b)** files synced + skills installed, **(c)** a correct, unique+slug so **(d)** `crbn up` mints an isolated stack.++### 2.2 Two identity sources (must both be right)++| Identity | Source | Drives | Code |+|---|---|---|---|+| **slug** | `$CARBON_WORKTREE` → `.carbon-worktree` file → `basename(worktreeRoot)` | Docker project `carbon-<slug>`, `~/.carbon/dev-ports.json` key, `CARBON_WORKTREE` | `worktree.ts:49-60`, `75-77` |+| **branchPrefix** | last `/`-segment of the git branch (sanitized), else slug | `DOMAIN`, `ERP_URL`/`MES_URL`/`SUPABASE_URL`, portless `*.dev` aliases | `portless.ts:390-402`, `env.ts:18-97` |++In a **native** worktree both are unique per worktree (slug = full dir basename+`carbon-feat-service`; prefix = `service`). Under **Conductor** the slug is forced+to `$CONDUCTOR_WORKSPACE_NAME`, which is neither guaranteed unique nor+branch-aligned, while the prefix is still branch-derived — hence+`CARBON_WORKTREE=carbon` but `DOMAIN=featuser-select.dev` in this workspace.++### 2.3 Conductor config today (legacy `conductor.json`, committed)++`conductor.json` (repo root, identical in main/moscow/macau):++```json+{+ "scripts": {+ "setup": "echo \"$CONDUCTOR_WORKSPACE_NAME\" > .carbon-worktree && pnpm install && ./packages/dev/bin/crbn env sync && bash .ai/scripts/install-skills.sh",+ "run": "./packages/dev/bin/crbn up --all",+ "archive": "./packages/dev/bin/crbn down --volumes"+ }+}+```++Facts that matter for the redesign:+- Conductor treats `conductor.json` as **legacy**; the modern form is+ `.conductor/settings.toml`. There is currently **no `.conductor/` dir**.+- Conductor reuses a physical codename dir across successive workspaces (symlinks+ accumulate; `git worktree list` shows a `prunable` reused dir). A reused dir can+ carry a **stale `.carbon-worktree`** from a prior occupant.+- Conductor **strips slashes** from branch names (`feat/user-select` →+ `featuser-select`), so its `branchPrefix` differs from native crbn's.+- Conductor's `archive` runs `crbn down --volumes`, which tears down containers ++ volumes but **does not free the registry slot** (only `crbn remove` calls+ `removeSlot`, `remove.ts:159`). Orphan slots accumulate.++---++## 3. Goals / Non-goals++**Goals**+1. A Conductor-created workspace boots via `crbn up` into a fully isolated stack,+ identical in shape to a `crbn checkout` worktree.+2. The slug is **deterministic, unique, and never collides** with the main+ checkout or sibling workspaces — regardless of physical path or codename reuse.+3. slug and domain are derived from a single, predictable rule (no more+ `carbon` vs `featuser-select.dev` split-brain).+4. The provisioning logic is a **first-class, idempotent crbn command** (usable by+ Conductor, by native users adopting a hand-made `git worktree add`, and by CI),+ not a one-off shell incantation embedded in `conductor.json`.+5. Migrate repo config to the supported `.conductor/settings.toml`.++**Non-goals**+- Changing how the main checkout or native `crbn new`/`checkout` worktrees behave+ (parity means Conductor matches them, not vice-versa).+- Changing Conductor's own `git worktree add` path/codename scheme (out of our+ control; we adapt to it).+- Sharing databases across workspaces (that's the existing `crbn up --borrow`+ opt-in; unchanged).++---++## 4. Proposed design++Two parts. Part A is the substance (a crbn command); Part B is the thin Conductor+wrapper that calls it.++### Part A — `crbn init`: provision the current worktree++Add an idempotent subcommand (working name **`crbn init`**; alt: `adopt` /+`provision`) that makes *the worktree it is run in* look exactly like one produced+by `crbn checkout`, then leaves the heavy stack boot to `crbn up`:++1. **Compute + persist a canonical slug** (see §5) via `persistSlug`+ (`worktree.ts:62`), overwriting any stale `.carbon-worktree`. This is the fix+ for the collision and the codename-reuse staleness.+2. **`env sync`** — copy `package.json#crbn.copy` files (today `[".env"]`) from the+ main checkout (`copy.ts` `envSync`).+3. **Install skills** — run `.ai/scripts/install-skills.sh` (symlink `.ai/rules` ++ `.ai/skills` into `.claude`/`.codex`), matching `do_post_create`.+4. **Idempotent + path-agnostic**: safe to re-run; resolves the main checkout via+ `--git-common-dir` (already how `bin/crbn:repo_root` works), so it works from+ any path including Conductor's.+5. *(Optional, see §9-D)* pre-allocate the slot and write `.env.local` so the env+ exists before the stack is booted. `crbn up` already does this idempotently, so+ this is a convenience, not a requirement.++Then refactor `do_post_create` (bash, `bin/crbn:404-417`) and the `.env` copy in+`new.ts:62-74` to call `crbn init`, so **one code path** provisions worktrees for+`new`, `checkout`, and Conductor. This removes today's drift where `new` copies+`.env` inline but skips `env sync`/skills while `checkout` does both.++`initWorktree` takes an explicit `{ root }` and threads it through every step+(`persistSlug(root)`, `syncStaleCopyFiles(root)`, `installSkills` via+`execa(…, { cwd: root })`) rather than trusting `process.cwd()`. **`new` must+pass `root: targetPath`** — the freshly-created worktree, not the caller — so+provisioning lands there. The bash `checkout`/Conductor paths run init with+their cwd already inside the target, so the `root` default (`getWorktreeRoot()`)+resolves correctly. Covered by `init.test.ts` (asserts `.carbon-worktree` is+written under the target, never the main checkout).++### Part B — Conductor config → `.conductor/settings.toml`++Replace committed `conductor.json` with `.conductor/settings.toml`:++```toml+"$schema" = "https://conductor.build/schemas/settings.repo.schema.json"++[scripts]+setup = "pnpm install && ./packages/dev/bin/crbn init"+run_mode = "concurrent" # workspaces are port-isolated by crbn+archive = "./packages/dev/bin/crbn remove --path . --yes" # frees the registry slot too (see §6)++[scripts.run.dev]+command = "./packages/dev/bin/crbn up --all"+default = true+icon = "rocket"+```++Key changes vs today:+- **Slug no longer comes from `$CONDUCTOR_WORKSPACE_NAME`.** `crbn init` owns it+ (§5), killing the `carbon` collision.+- `env sync` + `install-skills` fold into `crbn init` (single source of truth).+- `run_mode = "concurrent"` is correct because crbn already isolates ports/DB per+ slug (the whole point of the slot registry).+- `archive` frees the slot, not just the containers (§6).++**Rollout caveat:** Conductor only honors a `settings.toml` change **after it is+merged to the default branch on the remote** (`origin/main`). Until then it keeps+reading the committed `conductor.json`. So we can either (i) ship `crbn init` ++fix `conductor.json` in the same PR for an immediate effect on the current legacy+path, then (ii) migrate to `settings.toml` — or do both in one PR and accept that+the TOML only activates post-merge. See §8.++---++## 5. Slug derivation — the central decision++The slug must be unique per worktree, stable, and ideally aligned with native+crbn. Candidates:++- **(R) Branch-derived, repo-prefixed** — `slug = "<repoBase>-<slugify(branch)>"`+ (e.g. `carbon-featuser-select`). Read the *current* branch via git inside+ `crbn init`.+ - ✅ Identical **shape** to native worktrees (`carbon-feat-service`), so+ `crbn list`/`status` show Conductor + native worktrees uniformly.+ - ✅ Deterministic, branch-aligned (slug and domain now tell the same story).+ - ✅ Never collides with main (`carbon`) or siblings (distinct branches).+ - ⚠️ On Conductor **codename reuse** (archive → recreate on the same physical+ dir with a new branch) the slug changes, so the old slot orphans in the+ registry — mitigated by the §6 archive change (`crbn remove` frees it).+- **(B) Path/codename-derived** — drop the `echo` line entirely and let+ `resolveSlug` fall back to `basename(worktreeRoot)` = `moscow`/`macau`.+ - ✅ Minimal change; already unique across Conductor dirs; reuses the same slot+ on codename reuse (no orphan).+ - ❌ Not branch-aligned (slug `moscow`, domain `featuser-select.dev` split-brain+ persists); doesn't match native shape; a reused dir silently reuses a prior+ branch's DB unless volumes were wiped.++**Recommendation: (R) branch-derived, repo-prefixed**, because it most literally+satisfies "do the same thing as `crbn checkout`" and eliminates the split-brain.+Pair it with the §6 archive fix so orphan slots don't accumulate. (Option B is the+acceptable low-effort stopgap if we only want to stop the bleeding — see §8.)++Uniqueness guard: `crbn init` should still call `ensureSlugAvailable`+(`worktree.ts:95`) and, on the (rare) event that the branch-derived slug is taken+by a *different* live path, fall back to appending a short disambiguator or the+codename. Two git worktrees can't share a branch, so collisions only arise from+stale/misconfigured state.++---++## 6. Archive / registry-slot lifecycle++Today `archive = crbn down --volumes` stops the stack but leaves the+`~/.carbon/dev-ports.json` entry behind (`down.ts` never calls `removeSlot`). With+branch-derived slugs (§5-R), that means an orphan per archived workspace. Fix by+having archive free the slot. Options:++- Point archive at a **non-interactive** teardown that removes the slot. `crbn+ remove` already does `removeSlot` (`remove.ts:159`) but is interactive+ (multi-select). This spec assumes we add non-interactive flags+ (`crbn remove --path . --yes`) or a `crbn down --purge` that also calls+ `removeSlot` + flushes the redis DB index. **Decision in §9-C.**++---++## 7. Edge cases++- **Main branch / main checkout.** Conductor workspaces are always on a feature+ branch, never `main`, so `slug = carbon-<branch>` never regenerates the main+ checkout's `carbon`. `crbn init` still refuses to run in the main checkout to+ avoid clobbering `carbon`, via `isLinkedWorktree(root)` — it compares the+ normalized `git-dir` and `git-common-dir` (equal in the main worktree, differ+ in linked worktrees). (Comparing `--git-common-dir` to `cwd` would be+ unreliable — they aren't equal even in the main checkout.) Guard covered by+ `init.test.ts`.+- **Codename reuse with stale `.carbon-worktree`.** `crbn init` overwrites the+ slug file every run, so a reused dir is corrected on setup. (Today's `echo` also+ overwrites, but with the wrong value.)+- **Branch rename after creation.** Domain (branchPrefix) follows the branch on the+ next `crbn up`; slug stays put (keyed in the registry). Acceptable and matches+ native behavior. If we want slug to track renames too, that's a separate+ `crbn init --reslug`.+- **Slash-stripped branch names.** Conductor's `featuser-select` vs a native+ `feat/user-select` yields different prefixes/slugs. Cosmetic; note it. Not worth+ fighting Conductor's sanitizer.+- **PR workspaces.** Native `crbn checkout <pr#>` sets push-back tracking; Conductor+ has its own PR flow (`.context/attachments/.../PR instructions.md`). Out of scope+ — `crbn init` only provisions env; it doesn't manage PR tracking.+- **`.context` dir.** Conductor-managed, locally git-excluded; untouched.++---++## 8. Rollout plan++Because `settings.toml` activates only post-merge, sequence to avoid a broken+in-between state:++1. **PR 1 (crbn):** add `crbn init` (+ non-interactive `crbn remove`/`down --purge`+ per §9-C), refactor `do_post_create`/`new` to use it, unit tests+ (`packages/dev/src/*.test.ts` style). No behavior change for existing users of+ `new`/`checkout` beyond consolidation.+2. **PR 1 also:** fix the **legacy** `conductor.json` `setup` to+ `pnpm install && ./packages/dev/bin/crbn init` and `archive` to the+ slot-freeing teardown — this takes effect immediately on the current legacy+ path and fixes the `moscow`↔`carbon` collision without waiting on TOML.+3. **PR 2 (config migration):** add `.conductor/settings.toml` (Part B) and delete+ `conductor.json`. Takes effect once merged to `origin/main`. Verify Conductor+ picks it up on the next new workspace.+4. **One-time cleanup** on dev machines: `crbn remove` the stale `carbon`-slug+ Conductor entry, or re-run `crbn init && crbn up` in existing Conductor+ workspaces to re-slug them.++---++## 9. Open questions / decisions (recommendations — please veto)++- **A. Command name.** `crbn init` vs `crbn adopt` vs `crbn provision`.+ *Recommend `crbn init`* (shortest; "make this dir a ready Carbon worktree").+- **B. Slug policy.** §5. *Recommend (R) branch-derived, repo-prefixed+ `carbon-<slugify(branch)>`.*+- **C. Archive teardown.** Add `crbn remove --path . --yes` (non-interactive) vs a+ new `crbn down --purge`. *Recommend extending `crbn remove` with+ `--path`/`--yes`* (reuses its existing `removeSlot` + redis-flush path;+ `down --purge` would duplicate that logic).+- **D. Should `crbn init` also write `.env.local` (pre-allocate the slot), or leave+ that to `crbn up`?** *Recommend leaving it to `crbn up`* to keep `init` cheap and+ side-effect-light; revisit if tools need `.env.local` present pre-boot.+- **E. Migrate to `settings.toml` now, or just fix `conductor.json`?** *Recommend+ both, sequenced per §8* — fix the legacy file for an immediate effect, migrate to+ TOML for the supported long-term config.+- **F. Keep `run_mode = "concurrent"`?** *Recommend yes* — crbn's slot registry+ already guarantees per-workspace port/DB isolation, which is exactly the+ precondition for concurrent runs.++---++## 10. Acceptance criteria++- Creating a fresh Conductor workspace on branch `feat/x` results in:+ - `.carbon-worktree` = `carbon-feat-x` (or the §9-B chosen scheme), **never**+ `carbon` and never equal to any other live worktree's slug.+ - `~/.carbon/dev-ports.json` gains a distinct entry pointing at the workspace+ path; `crbn up --all` boots without an `ensureSlugAvailable` error and with a+ port set disjoint from main and siblings.+ - `.env.local` `CARBON_WORKTREE` and `DOMAIN` tell a consistent story+ (`carbon-feat-x` / `x.dev` or `feat-x.dev` per Conductor's branch sanitizer).+ - `.claude`/`.codex` skill symlinks present; `.env` copied from main.+- Booting the main checkout and the Conductor workspace **simultaneously** works+ (no shared Docker project, no port clash).+- Archiving the workspace frees its registry slot (no orphan in+ `~/.carbon/dev-ports.json`).+- `crbn new` / `crbn checkout` behavior for native worktrees is unchanged+ (verified by existing `packages/dev` tests + a manual `crbn new` smoke).++---++## 11. Risks++- **Config-activation lag:** `settings.toml` only applies post-merge to main;+ mitigated by fixing `conductor.json` in the same PR (§8).+- **Refactoring `do_post_create`/`new` to share `crbn init`** could regress native+ worktree creation — cover with tests + a manual smoke before merge.+- **Re-slugging existing Conductor workspaces** changes their Docker project name,+ so the old `carbon-carbon`/`carbon-macau` stacks + volumes orphan until cleaned+ up (one-time `crbn remove`, §8-4). Data in those dev stacks is disposable.+- **Branch-derived slug + codename reuse** without the §6 archive fix would leak+ registry entries — the two changes must ship together.++---++## Appendix — key files++- `packages/dev/bin/crbn` — bash router; `cmd_checkout` (173-296),+ `do_post_create` (404-417), `repo_root` (63-75).+- `packages/dev/src/commands/new.ts` — `newWorktree` (dir + `.env` copy).+- `packages/dev/src/commands/up.ts` — `provisionSlot`/`resolveSlug`/`persistSlug`+ (168-360).+- `packages/dev/src/worktree.ts` — `resolveSlug` (49-60), `resolveSlot`+ (134-166), `ensureSlugAvailable` (95-120), registry `~/.carbon/dev-ports.json`.+- `packages/dev/src/env.ts` — `renderEnv`/`writeEnv` (`.env.local`).+- `packages/dev/src/services/portless.ts` — `branchToPrefix` (390-402).+- `packages/dev/src/commands/remove.ts` — `removeSlot` (159).+- `packages/dev/src/commands/copy.ts` — `envSync` (`package.json#crbn.copy`).+- Repo config: `conductor.json` (legacy) → `.conductor/settings.toml` (target).+</content>diff --git a/.ai/specs/2026-07-14-user-select-rewrite.md b/.ai/specs/2026-07-14-user-select-rewrite.mdnew file mode 100644index 0000000000..df6c8cb9c1--- /dev/null+++ b/.ai/specs/2026-07-14-user-select-rewrite.md@@ -0,0 +1,252 @@+# User Select Performance Rewrite++> Status: draft+> Author: Brad Barbin + Claude+> Date: 2026-07-14++## TLDR++Rewrite the `UserSelect` data layer (and the `EmailRecipients` picker that shares its data source) around lazy, paginated, purpose-built endpoints cached in the existing `window.clientCache` (TanStack QueryClient) pattern. The recursive `groups` view — which walks the **entire multi-tenant `membership` table and `jsonb_agg`s full user rows on every open** — leaves the hot path entirely. The bespoke tree combobox shell is kept; interactions change so a group row is click-to-select with a separate chevron to expand, search returns a flat non-expandable list of groups + people, top-level groups load in pages with infinite scroll, and preselected values hydrate from a single mixed-id resolve endpoint.++## Problem Statement++Every open of the user select fetches `/api/users/groups?type=…`, which reads the `groups` view (`20230123004632_groups.sql`). That view has three structural performance problems, all verified in the SQL:++1. **Cross-tenant recursive scan.** `groups` aggregates over `groups_recursive`, a recursive view over ALL memberships of ALL companies. The route's `.eq("companyId", companyId)` cannot be pushed down into a recursive CTE — Postgres computes the full walk, then filters.+2. **Eager `jsonb_agg` of whole user rows.** The view aggregates `to_jsonb(u)` per group even when the caller omits the `users` column from its select.+3. **Multi-row duplication.** A nested group appears once per parent path *and* once at the root (the recursive view's base case emits every membership row with `parentId = NULL`), which is why `users.groups.$groupId.members.tsx` needs a `.limit(1).maybeSingle()` workaround, and why `arrayToTree` receives duplicate ids.++On top of the query cost: the whole group tree is fetched up-front (structure for every group, members already lazy per group), search covers users only (groups are not searchable), preselected group ids can only be labeled by loading the entire tree, and there is no pagination — a company with hundreds of groups renders them all.++`EmailRecipients.tsx` is worse: it uses the `?include=users` variant (`groupsByTypeWithUsers`) — the full recursive tree **with** every member's user JSON — flattened client-side just to build email options.++## Proposed Solution++Keep the bespoke tree-combobox shell (`apps/erp/app/components/Selectors/UserSelect/`) and its WAI-ARIA keyboard model. Replace the data layer with five thin endpoints backed by two new plpgsql RPCs that query `group`/`membership` directly (indexed, company-scoped, non-recursive), cached read-through in `window.clientCache` via `fetchQuery`, invalidated by `clientAction`s on every group-mutating route.++### Data-fetching strategy++| Interaction | Request | Notes |+|---|---|---|+| Open (empty input) | `GET /api/users/select/groups?type=&offset=0&limit=25` | Top-level groups only, with member counts. No user rows. |+| Scroll to bottom of list | same, `offset += 25` | Infinite scroll; pages accumulate in component state. |+| Expand a group (or hover-prefetch) | `GET /api/users/select/groups/:groupId/members` | Direct child groups (with counts) + direct active users. Works at every nesting depth. |+| Type ≥ 2 chars (240 ms debounce) | `GET /api/users/select/search?q=&type=&excludeSelf=&allowedIds=` | Flat result: matching groups (all levels, not just top-level) + matching users. Nothing expandable. |+| Mount with preselected ids | `GET /api/users/select/resolve?ids=a,b,c` | Mixed user/group ids → `{ users, groups }` so chips render immediately. |+| EmailRecipients selects a group | `GET /api/users/select/groups/:groupId/emails` | Recursive member emails via existing `users_for_groups`-based `getGroupEmails`. |++1-character input filters the already-loaded pages client-side (parity with today's `< 2 chars` behavior).++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Component shell | Keep bespoke tree combobox (`UserSelect/` + `useUserSelect.ts`); no cmdk rebuild | User decision 2026-07-14. Expand/collapse of children is a kept behavior; perf problem is data, not rendering; ~31 consumer files depend on current behavior. |+| Caching | Existing imperative `window.clientCache` pattern — **no** `QueryClientProvider`, no hooks | User decision 2026-07-14 ("we already have a react query pattern — use that"). Component fetches go through `clientCache.fetchQuery({ queryKey, staleTime, queryFn })`, which gives read-through caching, staleness, and concurrent-call dedupe with the existing client. |+| Cache invalidation | `clientAction`s on every route that mutates groups/memberships (matrix below) call a shared `invalidateUserSelectQueries(companyId)` | User directive: "be sure to clear the cache when we modify/add groups." Today only `groups.new` and `employees.new` invalidate — group **edit/delete** do not; this fixes that gap. |+| Scope | `EmailRecipients` migrates in v1 too | User decision 2026-07-14. Removes the last consumer of the eager `?include=users` endpoint. |+| Type filters | `type="employee" \| "customer" \| "supplier"` and `queryFilters` (`excludeSelf`, `allowedIds`) stay as props; every new endpoint takes them as params | User directive 2026-07-14. Flag semantics identical to the current route: `employee` → all non-customer/supplier flags false-filtered; `customer` → `isCustomerTypeGroup OR isCustomerOrgGroup`; `supplier` → mirror. |+| Group row semantics | Row click **selects** the group; the chevron (separate hit target) expands/collapses; hover still prefetches members. Applies at every depth, not just top level. In `usersOnly` mode groups are not selectable, so row click expands (parity). The redundant "group as first child item" row is removed. | User decision: top-level node is both selectable and expandable when browsing; search results have nothing to expand. |+| Search results | Flat, non-expandable: Groups section then People section. In `usersOnly` mode only people are shown (an unselectable, unexpandable group row would be dead UI). | User's point 2c; groups become name-searchable for the first time. |+| "Top-level" definition | The seeded per-company roots ("All Employees" `00000000-0000-…`, "All Customers" `11111111-1111-…`, "All Suppliers" `22222222-2222-…`) plus direct children of those roots plus groups that are not a member of any group. Roots stay visible, selectable, pinned first. | Matches the real hierarchy (type groups are auto-nested under deterministic-uuid roots by triggers; custom groups are parentless). Roots are genuinely useful "everyone" targets and exist in today's data. |+| Sort order | `is_root DESC, is_type_group DESC, name ASC, id ASC` | Parity with the old view's `isEmployeeTypeGroup DESC … name ASC` while being deterministic for offset pagination. |+| Pagination style | Offset + limit (25/page), `hasMore` via `limit + 1` fetch | Groups change rarely; offset matches table conventions (`setGenericQueryFilters`/`.range()`); cursor precedent exists only for the append-heavy ledger feed. |+| New SQL | One migration adding two `plpgsql` `STABLE SECURITY INVOKER` functions; **no table changes, no changes to existing views/RPCs** | `plpgsql` because PostgREST can drop a `LANGUAGE sql` function's internal `ORDER BY` (known lesson). Existing views/RPCs stay for admin pages and document-RLS (`groups_for_user` / `users_for_groups` untouched). |+| Member counts | `userCount` = direct active member users; `groupCount` = direct child groups. Tree rows show **no count badge** (2026-07-14 user directive) — counts drive expandability (`userCount + groupCount > 0` → chevron) and `usersOnly` filtering only; "N members" appears solely on search-result rows and in EmailRecipients. | Direct counts are one indexed aggregate; recursive counts would reintroduce the recursive walk. EmailRecipients' count becomes direct-count (was recursive unique-email count) — accepted trade-off; emails still resolve recursively on selection. |+| Members on expand | All direct members, un-paginated | Parity with today (the old view aggregated all of them anyway); bounded by real group sizes. |+| Empty groups in `usersOnly` | Hidden when `userCount = 0 AND groupCount = 0` | Parity with today's "group with no known members is filtered out"; a group with child groups stays visible since descendants may hold users. |+| Value contract | `UserSelectProps` unchanged: `value` = raw ids, `onChange(IndividualOrGroup[])`. Group selection items keep a `users` key (empty array when not loaded) so the `"users" in item` discriminator used by `Users.tsx` `verbose` mode keeps working; `memberCount` added. `onExplode` fetches members on demand before exploding. | 31 wrapper call sites compile and behave unchanged. |+| Old endpoints | `users.groups.tsx`, `users.groups.$groupId.members.tsx`, `users.search.tsx`, `users.batch.tsx` + their `path.to.api.*` helpers + `groupsByTypeQuery` are **deleted** once both components migrate (they have no other consumers — verified) | "Never leave stale endpoints." Admin pages (`getGroups`/`groups_query`, `getGroupMembers`) don't use these routes and are out of scope. |+| Permissions | New routes use `requirePermissions(request, { role: "employee" })` + explicit `companyId` scoping in every query/RPC | Parity with the existing select endpoints; these serve option lists, not module data. |+| User search scoping | Users are matched via `ilike` on `fullName` against the **`groupMembers` view** — active users who are members of this company's groups, filtered by the same type flags as the group list; deduped per user, limit 20 (2026-07-14 revision after user feedback) | Consistency by construction: search finds exactly the people the tree can reach (member lists filter on `user.active` only). The earlier `userToCompany` inner-join scoping used a different population rule than the tree, which read as "missing users". |+| Generated types | RPC/response typing via `Awaited<ReturnType<…>>` casts in the service; do **not** commit a local `pnpm db:types` regeneration | Committed types are cloud-generated; local regen produces a huge wrong diff (known reference). |+| Competitor research | Skipped — not an ERP-domain feature | This is a frontend data-fetching pattern (async tree select, keyset/offset paging); design anchors on internal precedent (`InfiniteScroll.tsx`, ledger-activity pagination, clientLoader caching) instead of `.ai/research/`. |++### Heuristics checklist++| # | Heuristic | Answer |+|---|-----------|--------|+| 1 | Multi-tenancy | No new tables. New RPCs take `p_company_id` and filter on it; the legacy `group` table (single-col PK, nullable `companyId`, no RLS) is unchanged — pre-existing gap noted in Risks. |+| 2 | Service shape | New functions in `users.service.ts` take `client` first, return `{ data, error }`, never throw. |+| 3 | RLS coverage | No new tables. RPCs are `SECURITY INVOKER`, so existing `membership`/`user` RLS applies to the caller. |+| 4 | Permission scoping | `role: "employee"` on all five routes (parity with the routes they replace). |+| 5 | Form pattern | N/A — no new forms; existing wrappers (`Users`, `Employees`, `User`) unchanged. |+| 6 | Module layout | Service/model additions go in `apps/erp/app/modules/users/users.service.ts` / `types.ts`; UI stays in `components/Selectors/UserSelect/`. |+| 7 | Backward compatibility | Public component props unchanged; old API routes deleted only after both consumers migrate in the same change; DB views/RPCs (`groups`, `groups_query`, `groups_for_user`, `users_for_groups`) untouched. |++## Data Model Changes++No table changes. One migration (`pnpm db:migrate:new user-select-rpcs`, randomized HHMMSS) adding two functions:++```sql+-- Paginated group list for the user select.+-- p_search NULL → top-level groups only (roots pinned first)+-- p_search set → ALL matching groups at any depth (flat search)+CREATE OR REPLACE FUNCTION get_user_select_groups(+ p_company_id TEXT,+ p_type TEXT DEFAULT NULL, -- 'employee' | 'customer' | 'supplier' | NULL+ p_search TEXT DEFAULT NULL,+ p_limit INT DEFAULT 25,+ p_offset INT DEFAULT 0+) RETURNS TABLE (+ "id" TEXT, "name" TEXT,+ "isEmployeeTypeGroup" BOOLEAN, "isCustomerOrgGroup" BOOLEAN,+ "isCustomerTypeGroup" BOOLEAN, "isSupplierOrgGroup" BOOLEAN,+ "isSupplierTypeGroup" BOOLEAN,+ "userCount" INT, "groupCount" INT, "isRoot" BOOLEAN+) LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ -- deterministic per-company root ids (see 20230123004632_groups.sql triggers)+ _roots TEXT[] := ARRAY[+ '00000000-0000-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12),+ '11111111-1111-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12),+ '22222222-2222-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12)+ ];+BEGIN+ RETURN QUERY+ SELECT g."id", g."name",+ g."isEmployeeTypeGroup", g."isCustomerOrgGroup", g."isCustomerTypeGroup",+ g."isSupplierOrgGroup", g."isSupplierTypeGroup",+ (SELECT count(*)::INT FROM "membership" m JOIN "user" u ON u."id" = m."memberUserId"+ WHERE m."groupId" = g."id" AND u."active" = TRUE) AS "userCount",+ (SELECT count(*)::INT FROM "membership" m+ WHERE m."groupId" = g."id" AND m."memberGroupId" IS NOT NULL) AS "groupCount",+ (g."id" = ANY(_roots)) AS "isRoot"+ FROM "group" g+ WHERE g."companyId" = p_company_id+ AND g."isIdentityGroup" = FALSE+ AND CASE+ WHEN p_type = 'employee' THEN NOT (g."isCustomerOrgGroup" OR g."isCustomerTypeGroup"+ OR g."isSupplierOrgGroup" OR g."isSupplierTypeGroup")+ WHEN p_type = 'customer' THEN (g."isCustomerTypeGroup" OR g."isCustomerOrgGroup")+ WHEN p_type = 'supplier' THEN (g."isSupplierTypeGroup" OR g."isSupplierOrgGroup")+ ELSE TRUE END+ AND CASE+ WHEN p_search IS NOT NULL AND p_search <> ''+ THEN g."name" ILIKE '%' || p_search || '%' AND NOT (g."id" = ANY(_roots))+ ELSE (+ g."id" = ANY(_roots)+ OR EXISTS (SELECT 1 FROM "membership" m+ WHERE m."memberGroupId" = g."id" AND m."groupId" = ANY(_roots))+ OR NOT EXISTS (SELECT 1 FROM "membership" m WHERE m."memberGroupId" = g."id")+ ) END+ ORDER BY (g."id" = ANY(_roots)) DESC,+ (g."isEmployeeTypeGroup" OR g."isCustomerTypeGroup" OR g."isSupplierTypeGroup") DESC,+ g."name" ASC, g."id" ASC+ LIMIT p_limit OFFSET p_offset;+END;+$$;++-- Direct members of one group: child groups (with counts) + active users.+CREATE OR REPLACE FUNCTION get_user_select_group_members(+ p_company_id TEXT,+ p_group_id TEXT+) RETURNS JSONB LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = public+AS $$+ -- { "groups": [{id, name, flags…, userCount, groupCount}],+ -- "users": [{id, firstName, lastName, fullName, email, avatarUrl}] }+ -- Guards g."companyId" = p_company_id via the parent group row; returns+ -- '{"groups":[],"users":[]}' when the group is not in the company.+ …+$$;+```++Both are additive and idempotent (`CREATE OR REPLACE`). The `groups` search branch and members lookup ride the existing indexes (`group_companyId_idx`, `index_membership_groupId`, `index_membership_memberGroupId`). `NOTIFY pgrst, 'reload schema';` at the end.++## API / Service Changes++### New routes (`apps/erp/app/routes/api+/`), all `role: "employee"`++| Route file | Path (`path.to.api.*`) | Serves | Backing |+|---|---|---|---|+| `users.select.groups.tsx` | `userSelectGroups(type, offset)` | `{ groups, hasMore }` first/next page of top-level groups | RPC `get_user_select_groups` (fetch `limit + 1`) |+| `users.select.groups.$groupId.members.tsx` | `userSelectGroupMembers(groupId)` | `{ groups, users }` direct members | RPC `get_user_select_group_members` |+| `users.select.search.tsx` | `userSelectSearch(q, type, filters)` | `{ groups, users }` flat search, ≥2 chars, limit 20 users / 10 groups | RPC (search branch) + `user` `ilike fullName` inner-joined to `userToCompany` on `companyId`, `active = true`, honoring `excludeSelf`/`allowedIds` |+| `users.select.resolve.tsx` | `userSelectResolve(ids)` | `{ users, groups }` for mixed preselected ids | `user.in("id", ids)` + `group.in("id", ids).eq("companyId", companyId)` with member counts |+| `users.select.groups.$groupId.emails.tsx` | `userSelectGroupEmails(groupId)` | `{ emails }` recursive member emails | existing `getGroupEmails` (`users_for_groups` → `getUserEmails`) |++### Service functions (`users.service.ts`)++`getUserSelectGroups`, `getUserSelectGroupMembers`, `searchUsersAndGroupsForSelect`, `resolveUserSelectIds` — all `(client, companyId, args)` → `{ data, error }`. RPC result typing via casts (no committed type regen).++### Caching (existing pattern, no provider)++- New factories in `apps/erp/app/utils/react-query.ts`:+ `userSelectGroupsQuery(companyId, type, offset)` (Low), `userSelectMembersQuery(companyId, groupId)` (Low), `userSelectSearchQuery(companyId, type, q, excludeSelf, allowedIds)` (High), `userSelectResolveQuery(companyId, sortedIds)` (Low), `groupEmailsQuery(companyId, groupId)` (Low).+- The component fetches through one helper: `window.clientCache.fetchQuery({ queryKey, staleTime, queryFn: () => fetch(url).then(r => r.json()) })` — read-through + staleness + in-flight dedupe (two selects on one page share requests). The current `searchCache` ref and raw uncached fetches are deleted.+- Shared helper `invalidateUserSelectQueries(companyId)` in `react-query.ts`: invalidate by predicate `queryKey[1] === companyId && queryKey[0] ∈ {userSelectGroups, userSelectMembers, userSelectSearch, userSelectResolve, groupEmails}`.++### Cache invalidation matrix (`clientAction`s)++| Route (`x+/users+/`) | Why | Today |+|---|---|---|+| `groups.new.tsx` | creates group + memberships | invalidates old key → **replace** |+| `groups.$groupId.tsx` | edits group + memberships | **missing today → add** |+| `groups.delete.$groupId.tsx` | deletes group | **missing today → add** |+| `employees.new.tsx` | trigger adds user to employee-type group | invalidates old key → **replace** |+| `employees.$employeeId.tsx` | employee-type change moves membership (trigger) | **add** |+| `deactivate.tsx` | deactivated users leave member lists/counts | **add** |+| `employee-types.new.tsx` / `employee-types.$employeeTypeId.tsx` / `employee-types.delete.$employeeTypeId.tsx` | triggers create/rename/remove the mirrored group | **add** |+| `customers.new.tsx` / `suppliers.new.tsx` (and `x+/customer+/new`, `x+/supplier+/new` if they create accounts) | interceptors create org groups / account memberships | **add** |++### Deletions (same change, after both components migrate)++Routes `users.groups.tsx`, `users.groups.$groupId.members.tsx`, `users.search.tsx`, `users.batch.tsx`; path helpers `groupsByType`, `groupsByTypeWithUsers`, `groupMembers`, `usersSearch`, `usersBatch`; key factory `groupsByTypeQuery`. (Verified only `useUserSelect.ts` and `EmailRecipients.tsx` consume them.) DB views/RPCs are **not** dropped — `groups_query` (admin GroupsTable), `groupMembers` view (group edit drawer), `groups_for_user`/`users_for_groups` (document RLS, approvals, MCP `users_getGroupEmails`) remain.++## UI Changes++### `UserSelect` (`components/Selectors/UserSelect/`)++- **Browse mode** (input < 2 chars): paged top-level groups. Group row = name + chevron (a spinner replaces the row's trailing slot while its members load; no count badge). **Row click selects the group** (adds/removes like any option); **chevron click expands** without selecting; hover prefetches members. Expanding renders direct users and child groups; child groups behave identically (selectable + expandable) at every depth. In `usersOnly` mode group rows aren't selectable — row click expands; groups with `userCount = 0 AND groupCount = 0` are hidden.+- **Infinite scroll**: sentinel row at the end of the top-level list via `useInView` (`react-intersection-observer`, already a dependency; the existing `InfiniteScroll` component's render-prop API doesn't fit the tree markup). Spinner row while a page loads; sentinel gone when `hasMore` is false.+- **Search mode** (≥ 2 chars, 240 ms debounce): flat sections — Groups (selectable rows, "Group" badge, member count, **no chevron**) then People. `usersOnly` shows People only. Clearing the input returns to browse mode (pages retained).+- **Selection state**: preselected `value` ids not yet in memory resolve through one `userSelectResolve` call → chips render name/avatar immediately. Group selection items keep `users: []` (discriminator for `Users.tsx` `verbose`) + `memberCount`; `onExplode` first fetches the group's members, then explodes (unchanged semantics: direct users).+- **Keyboard**: existing tree model preserved — Up/Down moves, Right/Left expands/collapses a focused group, Enter selects the focused row (now including group headers), Space toggles. Search mode is a flat list under the same navigation.+- Props unchanged (`isMulti`, `usersOnly`, `type`, `queryFilters`, `alwaysSelected`, `checkedSelections`, `showAvatars`, `resetAfterSelection`, …).++### `EmailRecipients` (`components/Form/EmailRecipients.tsx`)++- Keeps its cmdk chip-input UI. Data goes lazy: empty input shows the first page of top-level groups (with counts); typing ≥ 2 chars hits `userSelectSearch` (users include email); typing a raw valid email + Enter still adds it (unchanged).+- Selecting a user adds their email. Selecting a group fetches `userSelectGroupEmails(groupId)` and adds the deduped recursive member emails (today's semantics, resolved server-side instead of from the eager tree). Groups with `userCount = 0 AND groupCount = 0` hidden.+- No request to `groupsByTypeWithUsers` remains anywhere.++## Acceptance Criteria++- [ ] Opening a `<Users type="employee">` select issues exactly one request (`/api/users/select/groups?...offset=0`) returning at most 25 groups and zero user rows; nothing queries the `groups` view on this path (verify via Postgres logs or `EXPLAIN`-level inspection of the RPC).+- [ ] In a company with more than 25 top-level groups, scrolling the open list to the bottom loads the next page; every top-level group is reachable; the sentinel disappears on the last page.+- [ ] Clicking a group row (non-`usersOnly`) selects it immediately — no expansion required; clicking its chevron expands it without selecting; both work on nested groups. In `usersOnly` mode, row click expands and the group is not selectable.+- [ ] Expanding a group issues one members request and renders its direct users and child groups; re-expanding it (within staleness) issues zero network requests; hovering a collapsed group prefetches its members.+- [ ] Typing "eng" issues one debounced search request; results render as a flat Groups + People list with no chevrons; selecting a group from search adds it as a selection; clearing the input restores the browse tree without refetching page 0.+- [ ] A form whose `value` contains one user id and one group id renders both chips with correct names after a single `resolve` request, without the dropdown ever opening.+- [ ] Two user selects on the same page for the same `type` share the cache — the second mount issues zero group-page requests.+- [ ] After creating, renaming, or deleting a group; changing an employee's type; deactivating a user; or creating an employee type — the next open of any user select refetches fresh data (cache invalidated), without a full page reload.+- [ ] `EmailRecipients`: selecting a group adds all recursive member emails (deduped); no code path requests `groupsByTypeWithUsers`; manual email entry still works.+- [ ] `GroupsForm` (verbose `group_`/`user_` prefixes), `ApprovalRuleForm`, `DocumentForm` (`alwaysSelected`), and the read-only invite/deactivate modals compile and behave unchanged.+- [ ] Old routes/path helpers/`groupsByTypeQuery` are deleted; `rg "groupsByType|usersBatch|usersSearch|groupMembers\("` finds no live references.+- [ ] `pnpm exec turbo run typecheck --filter=erp` and `pnpm run lint` pass.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Behavior drift in the tree (duplicate-id `arrayToTree` quirks disappear; a group nested under multiple parents now appears under each parent lazily) | Low | This is strictly more correct; acceptance criteria pin the visible behaviors that must not drift (ordering, selection, counts). |+| `group` table has no RLS (pre-existing); RPCs could be called cross-tenant via PostgREST | Med | RPCs require `p_company_id` and filter on it; `membership`/`user` RLS still applies (SECURITY INVOKER). Adding `group` RLS is out of scope (auth-layer change — Ask First territory) and noted as follow-up. |+| Stale counts/lists for *other* users within `staleTime` (30 min) after someone else edits groups | Low | Same trade-off as every cached list in the app; own mutations invalidate immediately; staleTime tunable per key. |+| `EmailRecipients` badge shows direct member count instead of recursive unique-email count; browse mode no longer lists every user up-front | Low | Emails still resolve recursively and dedupe on selection; search covers users. Accepted in design review. |+| plpgsql RPC ordering/pagination bugs (offset drift when groups change between pages) | Low | Deterministic sort with `id` tiebreak; groups mutate rarely; duplicates de-duped client-side by id when accumulating pages. |+| Deleting old endpoints breaks an unnoticed consumer | Low | Consumer search verified (only the two components); acceptance criterion greps for stragglers; deletions land in the same PR as the migrations of both consumers. |+| Committed DB types don't know the new RPCs | Low | Service functions cast RPC results (`as` narrow types in `types.ts`); no local type regen committed (cloud-generated types reference). |++## Open Questions++> All resolved with the user on 2026-07-14 before this spec was written (spec-writing Step 5 / grill).++- [x] Keep the bespoke tree-combobox shell or rebuild on cmdk primitives? — **Answer (user):** Keep the bespoke shell; expand/collapse of children is a required behavior. Top-level (and nested) group nodes are both selectable and expandable when browsing; in search mode results are flat with nothing to expand.+- [x] Mount a `QueryClientProvider` + hooks (first hook-based react-query usage), or stay imperative? — **Answer (user):** Use the existing react-query pattern (`window.clientCache` imperative cache); no provider, no hooks. Must clear the cache whenever groups are modified/added — invalidation matrix above.+- [x] Leave `EmailRecipients` on the old eager endpoint for v1? — **Answer (user):** No — refactor `EmailRecipients` too; the eager `groupsByTypeWithUsers` path is removed entirely.+- [x] Do the type filters survive the rewrite? — **Answer (user):** Yes — keep supporting all filters (`employee`, `customer`, `supplier`, plus `queryFilters`) as props; all new endpoints take them as params.++## Changelog++- 2026-07-14: Created after grill interview; all open questions resolved pre-writing (shell kept, imperative react-query pattern, EmailRecipients in scope, filters preserved).diff --git a/.conductor/settings.toml b/.conductor/settings.tomlnew file mode 100644index 0000000000..1254ce9101--- /dev/null+++ b/.conductor/settings.toml@@ -0,0 +1,25 @@+"$schema" = "https://conductor.build/schemas/settings.repo.schema.json"++# Copy only `.env` (secrets) from the main checkout into each new workspace.+# NOT the default `.env*` — that would drag in the main checkout's `.env.local`+# (its ports/slug/domain); `crbn up` regenerates `.env.local` per worktree.+file_include_globs = ".env"++[scripts]+# Conductor creates the git worktree itself; `crbn init` then provisions it the+# same way `crbn checkout` does: a deterministic branch-derived slug+# (`.carbon-worktree`), `.env` synced from main, and .ai skills linked. This+# replaces the old `echo "$CONDUCTOR_WORKSPACE_NAME" > .carbon-worktree`, which+# produced non-unique slugs that collided with the main checkout's `carbon`.+setup = "pnpm install && ./packages/dev/bin/crbn init"+# Each worktree gets its own ports/DB/redis-slot (the crbn slot registry), so+# multiple workspaces can run their stacks at once.+run_mode = "concurrent"+# Full teardown when a workspace is archived: stop the stack, wipe volumes,+# flush redis, and release the port slot so the pool doesn't leak entries.+archive = "./packages/dev/bin/crbn down --purge"++[scripts.run.dev]+command = "./packages/dev/bin/crbn up --all"+default = true+icon = "rocket"diff --git a/apps/erp/app/components/Form/EmailRecipients.tsx b/apps/erp/app/components/Form/EmailRecipients.tsxindex 858dcaeca0..2a37f1e4c4 100644--- a/apps/erp/app/components/Form/EmailRecipients.tsx+++ b/apps/erp/app/components/Form/EmailRecipients.tsx@@ -20,15 +20,22 @@ import {import {type KeyboardEvent,useCallback,+ useEffect,useMemo,useRef,useState} from "react";import { LuUsers } from "react-icons/lu";-import { useFetcher } from "react-router";-import type { Group } from "~/modules/users";+import type { User, UserSelectGroup } from "~/modules/users";import { isValidEmail } from "~/utils/form";import { path } from "~/utils/path";+import {+ cachedApiQuery,+ getCompanyId,+ groupEmailsQuery,+ userSelectGroupsQuery,+ userSelectSearchQuery+} from "~/utils/react-query";type EmailRecipientsProps = {name: string;@@ -48,73 +55,83 @@ type GroupOption = {type: "group";id: string;name: string;- emails: string[];memberCount: number;};type Option = UserOption | GroupOption;-const useEmailOptions = (type: "employee" | "supplier" | "customer") => {- const groupsFetcher = useFetcher<{ groups: Group[] }>();+const toGroupOption = (group: UserSelectGroup): GroupOption => ({+ type: "group",+ id: group.id,+ name: group.name,+ memberCount: group.userCount+});++const useEmailOptions = (+ type: "employee" | "supplier" | "customer",+ inputValue: string+) => {+ const [topGroups, setTopGroups] = useState<UserSelectGroup[]>([]);+ const [searchResults, setSearchResults] = useState<{+ groups: UserSelectGroup[];+ users: User[];+ } | null>(null);useMount(() => {- groupsFetcher.load(path.to.api.groupsByTypeWithUsers(type));+ const companyId = getCompanyId();+ cachedApiQuery<{ groups: UserSelectGroup[]; hasMore: boolean }>(+ userSelectGroupsQuery(companyId, type, 0),+ path.to.api.userSelectGroups(type, 0)+ )+ .then((data) => setTopGroups(data.groups))+ .catch(() => setTopGroups([]));});- const options = useMemo<Option[]>(() => {- if (!groupsFetcher.data?.groups) return [];-- const opts: Option[] = [];- const seenGroupIds = new Set<string>();+ const q = inputValue.trim();- const collectGroupEmails = (group: Group): string[] => {- const groupEmails: string[] = [];- group.data.users?.forEach((user) => {- if (user.email) groupEmails.push(user.email);- });- group.children?.forEach((child) => {- groupEmails.push(...collectGroupEmails(child));- });- return groupEmails;- };+ useEffect(() => {+ if (q.length < 2) {+ setSearchResults(null);+ return;+ }+ const companyId = getCompanyId();+ const timeout = setTimeout(() => {+ cachedApiQuery<{ groups: UserSelectGroup[]; users: User[] }>(+ userSelectSearchQuery(companyId, type, q, ""),+ path.to.api.userSelectSearch(q, type)+ )+ .then(setSearchResults)+ .catch(() => setSearchResults(null));+ }, 240);+ return () => clearTimeout(timeout);+ }, [q, type]);- const processGroup = (group: Group) => {- if (seenGroupIds.has(group.data.id)) return;- seenGroupIds.add(group.data.id);+ const options = useMemo<Option[]>(() => {+ const hasMembers = (g: UserSelectGroup) => g.userCount + g.groupCount > 0;- const groupEmails = [...new Set(collectGroupEmails(group))];- if (groupEmails.length > 0) {- opts.push({- type: "group",- id: group.data.id,- name: group.data.name,- emails: groupEmails,- memberCount: groupEmails.length- });- }+ if (q.length >= 2 && searchResults) {+ const opts: Option[] = searchResults.groups+ .filter(hasMembers)+ .map(toGroupOption);- group.data.users?.forEach((user) => {- if (user.email) {+ const seenEmails = new Set<string>();+ searchResults.users.forEach((user) => {+ if (user.email && !seenEmails.has(user.email)) {+ seenEmails.add(user.email);opts.push({type: "user",id: user.id,- name: user.fullName,+ name: user.fullName ?? "",email: user.email});}});- };- groupsFetcher.data.groups.forEach(processGroup);+ return opts;+ }- const seenEmails = new Set<string>();- return opts.filter((opt) => {- if (opt.type === "group") return true;- if (seenEmails.has(opt.email)) return false;- seenEmails.add(opt.email);- return true;- });- }, [groupsFetcher.data]);+ return topGroups.filter(hasMembers).map(toGroupOption);+ }, [topGroups, searchResults, q]);return options;};@@ -137,21 +154,13 @@ export default function EmailRecipients({const [open, setOpen] = useState(false);const inputRef = useRef<HTMLInputElement>(null);- const options = useEmailOptions(type);+ const options = useEmailOptions(type, inputValue);- // Filter options based on search+ // Server search covers >= 2 chars; filter the mounted groups for shorter inputconst filteredOptions = useMemo(() => {- if (!inputValue.trim()) return options;- const search = inputValue.toLowerCase();- return options.filter((opt) => {- if (opt.type === "user") {- return (- opt.name.toLowerCase().includes(search) ||- opt.email.toLowerCase().includes(search)- );- }- return opt.name.toLowerCase().includes(search);- });+ const search = inputValue.trim().toLowerCase();+ if (!search || search.length >= 2) return options;+ return options.filter((opt) => opt.name.toLowerCase().includes(search));}, [options, inputValue]);const addEmail = useCallback(@@ -211,11 +220,22 @@ export default function EmailRecipients({}};- const handleSelect = (option: Option) => {+ const handleSelect = async (option: Option) => {if (option.type === "user") {addEmail(option.email);} else {- addEmails(option.emails);+ try {+ const companyId = getCompanyId();+ const { emails: groupEmails } = await cachedApiQuery<{+ emails: string[];+ }>(+ groupEmailsQuery(companyId, option.id),+ path.to.api.userSelectGroupEmails(option.id)+ );+ addEmails(groupEmails);+ } catch {+ // leave the input as-is — selecting again retries+ }}setInputValue("");setOpen(false);diff --git a/apps/erp/app/components/Selectors/UserSelect/components/Popover.tsx b/apps/erp/app/components/Selectors/UserSelect/components/Popover.tsxindex 0d4223f6d8..88cefe7b65 100644--- a/apps/erp/app/components/Selectors/UserSelect/components/Popover.tsx+++ b/apps/erp/app/components/Selectors/UserSelect/components/Popover.tsx@@ -10,69 +10,47 @@ const Popover = ({ children }: PropsWithChildren) => {// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {- /* Build a triple linked-list (TreeNode[]) of focusable DOM Elements that are children-+ /* Build a triple linked-list (TreeNode[]) of the focusable tree items in+ DOM order, at any nesting depth.+type TreeNode {- id: string;- expandable: boolean;+ uid: string;+ expandable: boolean; // from data-expandable (group rows)previousId?: string;nextId?: string;- parentId? string;- }-+ parentId?: string; // nearest ancestor treeitem+ }*/focusableNodes.current = {};- /* First get the parents */- const parents: Element[] = [];- if (listBoxRef.current) {- let node = listBoxRef.current.firstElementChild;- let lastNode = listBoxRef.current.lastElementChild;-- while (node && node !== lastNode) {- parents.push(node);- node = node.nextElementSibling;- }-- if (node) {- parents.push(node);- }- }-- /* Then make a flat list with the children spliced in */- const nodes: [string, string | undefined][] = [];-- parents.forEach((parent) => {- nodes.push([parent.id, undefined]);- const group = parent.getElementsByTagName("ul");- if (group?.[0]) {- let child = group[0].firstElementChild;- let lastChild = group[0].lastElementChild;+ if (!listBoxRef.current) return;- while (child && child !== lastChild) {- nodes.push([child.id, parent.id]);- child = child.nextElementSibling;- }+ const elements = Array.from(+ listBoxRef.current.querySelectorAll<HTMLElement>('[role="treeitem"]')+ ).filter((el) => el.id);- if (child) {- nodes.push([child.id, parent.id]);- }+ const nodes: [string, string | undefined, boolean][] = elements.map(+ (el) => {+ const parent =+ el.parentElement?.closest<HTMLElement>('[role="treeitem"]');+ return [+ el.id,+ parent?.id || undefined,+ el.getAttribute("data-expandable") === "true"+ ];}- });+ );- /* Finally, create the triple linked list */for (let i = 0; i < nodes.length; i++) {- const [node, parent] = nodes[i];- const previous = nodes?.[i - 1];- const next = nodes?.[i + 1];+ const [uid, parentId, expandable] = nodes[i];- focusableNodes.current[node] = {- uid: node,- expandable: parent === undefined,- parentId: parent,- previousId: previous?.[0] || undefined,- nextId: next?.[0] || undefined+ focusableNodes.current[uid] = {+ uid,+ expandable,+ parentId,+ previousId: nodes[i - 1]?.[0] || undefined,+ nextId: nodes[i + 1]?.[0] || undefined};}}, [children, focusableNodes, listBoxRef]);diff --git a/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsxindex 9438f66199..34f5e2c134 100644--- a/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx+++ b/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx@@ -1,17 +1,20 @@import { cn, Spinner } from "@carbon/react";+import { useEffect } from "react";import { FaChevronRight } from "react-icons/fa";import { LuCheck, LuUsers } from "react-icons/lu";+import { useInView } from "react-intersection-observer";import { Avatar } from "~/components";import useUserSelectContext from "../provider";-import type { IndividualOrGroup, OptionGroup } from "../types";+import type { GroupNode, IndividualOrGroup } from "../types";import { isGroup } from "../useUserSelect";const UserTreeSelect = () => {const {aria: { listBoxProps },- groups,+ viewModel,innerProps: { isMulti },loading,+ loadMore,onMouseOver,refs: { listBoxRef }} = useUserSelectContext();@@ -29,8 +32,17 @@ const UserTreeSelect = () => {<div className="flex items-center justify-center py-4"><Spinner /></div>- ) : groups.length > 0 ? (- groups.map((group) => <Group key={group.uid} group={group} />)+ ) : viewModel.mode === "search" ? (+ <SearchResults />+ ) : viewModel.nodes.length > 0 ? (+ <>+ {viewModel.nodes.map((node) => (+ <GroupRow key={node.uid} node={node} />+ ))}+ {viewModel.hasMore && (+ <SentinelRow onVisible={loadMore} loading={viewModel.loadingMore} />+ )}+ </>) : (<p className="text-center text-sm text-muted-foreground py-4">No options found@@ -49,87 +61,263 @@ const ExpandIcon = ({ isExpanded }: { isExpanded: boolean }) => (/>);-const Group = ({ group }: { group: OptionGroup }) => {+/** Loads the next page of top-level groups when scrolled into view. */+const SentinelRow = ({+ onVisible,+ loading+}: {+ onVisible: () => void;+ loading: boolean;+}) => {const {- innerProps: { alwaysSelected },+ refs: { listBoxRef }+ } = useUserSelectContext();+ // Root must be the tree's own scrollport: the popover can be clipped by an+ // ancestor (drawer body overflow), which makes viewport-rooted observation+ // never intersect even when the user scrolls the list to the bottom.+ const { ref, inView } = useInView({+ threshold: 0,+ root: listBoxRef.current+ });++ useEffect(() => {+ if (inView && !loading) {+ onVisible();+ }+ }, [inView, loading, onVisible]);++ return (+ <div ref={ref} className="flex items-center justify-center py-2">+ {loading && <Spinner className="h-4 w-4" />}+ </div>+ );+};++/**+ * A group at any depth: the row selects the group (when groups are+ * selectable); the chevron expands/collapses; hovering prefetches members.+ */+const GroupRow = ({ node }: { node: GroupNode }) => {+ const {+ innerProps: { alwaysSelected, usersOnly },+ focusedId,+ onDeselect,onGroupCollapse,onGroupExpand,- prefetchGroup,- focusedId,onSelect,- onDeselect,- selectionItemsById,- loadingGroups+ prefetchGroup,+ selectionItemsById} = useUserSelectContext();- const isFocused = group.uid === focusedId;- const isExpanded = group.expanded && group.items.length > 0;+ const { group, uid, expanded, loading, members } = node;++ const isFocused = uid === focusedId;+ const isSelected = group.id in selectionItemsById;+ const isDisabled = alwaysSelected?.includes(group.id) ?? false;+ const canExpand = group.userCount + group.groupCount > 0;+ const isOpen = expanded && members !== null;+ const isEmpty =+ members !== null &&+ members.groups.length === 0 &&+ members.users.length === 0;++ const selectionItem = (): IndividualOrGroup => ({+ ...group,+ users: [],+ memberCount: group.userCount + group.groupCount,+ uid,+ label: group.name || ""+ });- const groupId = group.uid.split("_")[1];- const isLoading = groupId ? loadingGroups?.[groupId] : false;+ const handleRowClick = () => {+ if (usersOnly) {+ if (canExpand) {+ expanded ? onGroupCollapse(uid) : onGroupExpand(uid);+ }+ return;+ }+ if (isDisabled) return;+ if (isSelected) {+ onDeselect(selectionItem());+ } else {+ onSelect(selectionItem());+ }+ };return (- // biome-ignore lint/a11y/useAriaPropsSupportedByRole: suppressed due to migration<div- id={group.uid}+ id={uid}+ role="treeitem"tabIndex={0}+ data-expandable={canExpand ? "true" : "false"}+ aria-expanded={canExpand ? expanded : undefined}+ aria-selected={isSelected}+ aria-disabled={isDisabled}className="rounded-md outline-none"- aria-expanded={isExpanded}>{/* Group Header */}<div- role="treeitem"- aria-selected={isExpanded ? "true" : "false"}- onClick={() =>- group.expanded ? onGroupCollapse(group.uid) : onGroupExpand(group.uid)- }+ onClick={handleRowClick}onMouseEnter={() => {- if (!group.expanded) prefetchGroup(group.uid);+ if (!expanded) prefetchGroup(group.id);}}className={cn("flex cursor-pointer select-none items-center gap-2 rounded-md px-2 py-2 hover:bg-muted/50 text-sm",- isFocused && "bg-muted/50"+ isFocused && "bg-muted/50",+ isSelected && "bg-accent",+ isDisabled && "opacity-50 pointer-events-none")}>- <ExpandIcon isExpanded={isExpanded} />- <span className="flex-1 truncate">{group.name}</span>- {isLoading ? (- <Spinner className="h-3 w-3" />+ {canExpand ? (+ <button+ type="button"+ aria-label={expanded ? "Collapse group" : "Expand group"}+ onClick={(e) => {+ e.stopPropagation();+ expanded ? onGroupCollapse(uid) : onGroupExpand(uid);+ }}+ className="-m-1.5 flex items-center justify-center rounded-md p-1.5 hover:bg-muted pointer-events-auto"+ >+ <ExpandIcon isExpanded={expanded} />+ </button>) : (- <span className="text-[10px] font-normal">{group.items.length}</span>+ <span className="h-3 w-3 shrink-0" />)}++ {!usersOnly && (+ <div+ className={cn(+ "flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors",+ isSelected+ ? "border-primary bg-primary text-primary-foreground"+ : "border-muted-foreground/30 bg-background"+ )}+ >+ {isSelected && <LuCheck className="h-3 w-3" />}+ </div>+ )}++ <span className="flex-1 truncate">{group.name}</span>+ {loading && <Spinner className="h-3 w-3" />}</div>- {/* Group Items */}- {isExpanded && (+ {/* Direct members: child groups first, then users */}+ {isOpen && members && (<ul role="group" className="flex flex-col gap-0.5 py-1 pl-2">- {group.items.map((item) => {- const isDisabled = alwaysSelected?.includes(item.id) ?? false;- const isFocused = item.uid === focusedId;- const isSelected = item.id in selectionItemsById;+ {members.groups.map((child) => (+ <li key={child.uid}>+ <GroupRow node={child} />+ </li>+ ))}+ {members.users.map((item) => {+ const itemIsDisabled = alwaysSelected?.includes(item.id) ?? false;+ const itemIsFocused = item.uid === focusedId;+ const itemIsSelected = item.id in selectionItemsById;return (<Optionkey={item.uid}id={item.uid}item={item}- isDisabled={isDisabled}- isFocused={isFocused}- isSelected={isSelected}+ isDisabled={itemIsDisabled}+ isFocused={itemIsFocused}+ isSelected={itemIsSelected}onClick={- !alwaysSelected.includes(item.id)- ? () => (isSelected ? onDeselect(item) : onSelect(item))+ !itemIsDisabled+ ? () => (itemIsSelected ? onDeselect(item) : onSelect(item)): undefined}/>);})}+ {isEmpty && (+ <li className="px-2 py-1.5 text-xs text-muted-foreground">+ No members+ </li>+ )}</ul>)}</div>);};+/** Flat, non-expandable results: matching groups, then matching people. */+const SearchResults = () => {+ const {+ innerProps: { alwaysSelected },+ viewModel,+ focusedId,+ onDeselect,+ onSelect,+ selectionItemsById+ } = useUserSelectContext();++ if (viewModel.mode !== "search") return null;++ const { groups, users, searching } = viewModel;++ if (groups.length === 0 && users.length === 0) {+ return (+ <div className="flex items-center justify-center py-4">+ {searching ? (+ <Spinner />+ ) : (+ <p className="text-center text-sm text-muted-foreground">+ No options found+ </p>+ )}+ </div>+ );+ }++ const renderOption = (item: IndividualOrGroup) => {+ const isDisabled = alwaysSelected?.includes(item.id) ?? false;+ const isFocused = item.uid === focusedId;+ const isSelected = item.id in selectionItemsById;++ return (+ <Option+ key={item.uid}+ id={item.uid}+ item={item}+ isDisabled={isDisabled}+ isFocused={isFocused}+ isSelected={isSelected}+ onClick={+ !isDisabled+ ? () => (isSelected ? onDeselect(item) : onSelect(item))+ : undefined+ }+ />+ );+ };++ return (+ <div className="flex flex-col gap-1">+ {groups.length > 0 && (+ <>+ <p className="px-2 pt-1 text-xs font-medium text-muted-foreground">+ Groups+ </p>+ <ul role="group" className="flex flex-col gap-0.5">+ {groups.map(renderOption)}+ </ul>+ </>+ )}+ {users.length > 0 && (+ <>+ <p className="px-2 pt-1 text-xs font-medium text-muted-foreground">+ People+ </p>+ <ul role="group" className="flex flex-col gap-0.5">+ {users.map(renderOption)}+ </ul>+ </>+ )}+ </div>+ );+};+const Option = ({id,item,@@ -148,10 +336,7 @@ const Option = ({const name = item.label;const itemIsGroup = isGroup(item);const memberCount =- itemIsGroup && "users" in item- ? (item.users?.length ?? 0) +- ("children" in item ? (item.children?.length ?? 0) : 0)- : 0;+ itemIsGroup && "memberCount" in item ? (item.memberCount ?? 0) : 0;// Get avatar info for individualsconst avatarUrl = "avatarUrl" in item ? item.avatarUrl : null;@@ -198,7 +383,7 @@ const Option = ({<div className="flex min-w-0 flex-1 flex-col"><span className="truncate">{name}</span>{itemIsGroup && memberCount > 0 && (- <span className="text-xs text-muted-foreground">+ <span className="text-xs text-muted-foreground tabular-nums">{memberCount} {memberCount === 1 ? "member" : "members"}</span>)}diff --git a/apps/erp/app/components/Selectors/UserSelect/types.ts b/apps/erp/app/components/Selectors/UserSelect/types.tsindex 4c778b792a..79cf3f2f6e 100644--- a/apps/erp/app/components/Selectors/UserSelect/types.ts+++ b/apps/erp/app/components/Selectors/UserSelect/types.ts@@ -8,12 +8,12 @@ import type {RefObject} from "react";-import type { Group, User } from "~/modules/users";+import type { User, UserSelectGroup } from "~/modules/users";export type ComboBoxRefs = {containerRef: RefObject<HTMLDivElement>;inputRef: RefObject<HTMLInputElement>;- listBoxRef: RefObject<HTMLUListElement>;+ listBoxRef: RefObject<HTMLDivElement>;popoverRef: RefObject<HTMLDivElement>;buttonRef: RefObject<Element>;focusableNodes: MutableRefObject<Record<string, TreeNode>>;@@ -54,13 +54,6 @@ export interface UserSelectProps {) => void;}-export type OptionGroup = {- uid: string;- expanded: boolean;- items: IndividualOrGroup[];- name: string;-};-export type TreeNode = {uid: string;expandable: boolean;@@ -68,12 +61,6 @@ export type TreeNode = {previousId?: string;nextId?: string;};-export interface PopoverProps {- aria: HTMLAttributes<HTMLDivElement>;- children: ReactNode;- innerProps: UserSelectProps;- refs: ComboBoxRefs;-}interface SelectionOptions {uid: string;@@ -82,18 +69,49 @@ interface SelectionOptions {isPersistent?: boolean;}-type UserWithOptions = User & SelectionOptions;-type SelectionGroupWithOptions = Group["data"] & {- children?: Group[];+export type UserWithOptions = User & SelectionOptions;++/**+ * A selected (or selectable) group. `users` is always present — it is the+ * discriminator between users and groups ("users" in item) relied on by the+ * Form wrappers — but stays [] until the group is exploded.+ */+export type SelectionGroupWithOptions = UserSelectGroup & {+ users: User[];+ memberCount: number;} & SelectionOptions;export type IndividualOrGroup = UserWithOptions | SelectionGroupWithOptions;export type SelectionItemsById = Record<string, IndividualOrGroup>;+/** One group node in the lazily-loaded browse tree. */+export type GroupNode = {+ /** Path-scoped id: `${parentUid}_${groupId}_group` — unique per tree path. */+ uid: string;+ group: UserSelectGroup;+ expanded: boolean;+ loading: boolean;+ /** null until the group's direct members have been fetched. */+ members: { groups: GroupNode[]; users: UserWithOptions[] } | null;+};++export type UserSelectViewModel =+ | {+ mode: "browse";+ nodes: GroupNode[];+ hasMore: boolean;+ loadingMore: boolean;+ }+ | {+ mode: "search";+ groups: SelectionGroupWithOptions[];+ users: UserWithOptions[];+ searching: boolean;+ };+export interface SelectInputProps {aria?: Omit<InputHTMLAttributes<HTMLInputElement>, "size">;- errors?: import("@supabase/supabase-js").PostgrestError;inputValue: string;innerProps: UserSelectProps;loading: boolean;@@ -106,23 +124,11 @@ export interface SelectInputProps {onInputFocus: () => void;}-export interface UserTreeSelectProps {- aria: HTMLAttributes<HTMLUListElement>;- disabledSelections?: string[];- focusedId: string | null;- groups: OptionGroup[];- groupTypeFilter?: string;+export interface PopoverProps {+ aria: HTMLAttributes<HTMLDivElement>;+ children: ReactNode;innerProps: UserSelectProps;- instanceId: string;- itemOnSelect?: (selectableItem: IndividualOrGroup) => void;- itemOnStage?: (selectableItem: IndividualOrGroup) => void;- loading: boolean;- multi?: boolean;refs: ComboBoxRefs;- searchFilter?: string;- selectionItemsById: SelectionItemsById;- stagedSelectionsById?: SelectionItemsById;- visible?: boolean;}export interface UserSelectionGenericQueryFilters {diff --git a/apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/erp/app/components/Selectors/UserSelect/useUserSelect.tsindex 23db0efa10..751fce0711 100644--- a/apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts+++ b/apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts@@ -1,6 +1,5 @@import { getLogger } from "@carbon/logger";import { useDisclosure, useOutsideClick } from "@carbon/react";-import type { PostgrestError } from "@supabase/supabase-js";import debounce from "lodash/debounce";import words from "lodash/words";import type { AriaAttributes, ChangeEvent, KeyboardEvent } from "react";@@ -12,17 +11,31 @@ import {useRef,useState} from "react";-import { useFetcher } from "react-router";-import type { Group, User } from "~/modules/users";+import type {+ User,+ UserSelectGroup,+ UserSelectGroupMembers+} from "~/modules/users";import { path } from "~/utils/path";+import {+ cachedApiQuery,+ getCompanyId,+ userSelectGroupsQuery,+ userSelectMembersQuery,+ userSelectResolveQuery,+ userSelectSearchQuery+} from "~/utils/react-query";import type {+ GroupNode,IndividualOrGroup,- OptionGroup,+ SelectionGroupWithOptions,SelectionItemsById,TreeNode,UserSelectionGenericQueryFilters,- UserSelectProps+ UserSelectProps,+ UserSelectViewModel,+ UserWithOptions} from "./types";const defaultProps = {@@ -48,6 +61,8 @@ const defaultProps = {const logger = getLogger("erp", "user-select");+const PAGE_SIZE = 25;+export default function useUserSelect(props: UserSelectProps) {/* Inner Props */const innerProps = useMemo(@@ -58,17 +73,6 @@ export default function useUserSelect(props: UserSelectProps) {[props]);- /* Data Fetching */- const groupsFetcher = useFetcher<{- groups: Group[];- errors?: PostgrestError;- }>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- groupsFetcher.load(path.to.api.groupsByType(innerProps.type));- }, [innerProps.type]);-/* Refs */const containerRef = useRef<HTMLDivElement>(null);const inputRef = useRef<HTMLInputElement>(null);@@ -76,28 +80,37 @@ export default function useUserSelect(props: UserSelectProps) {const popoverRef = useRef<HTMLDivElement>(null);const buttonRef = useRef<Element>(null);const focusableNodes = useRef<Record<string, TreeNode>>({});+ const uidToGroupId = useRef<Record<string, string>>({});+ const resolveRequested = useRef<Set<string>>(new Set());const instanceId = useId();/* Disclosures */const dropdown = useDisclosure();- /* Fetch States */+ /* Data */+ const [topLevelGroups, setTopLevelGroups] = useState<UserSelectGroup[]>([]);+ const [hasMore, setHasMore] = useState(false);+ const [initialLoading, setInitialLoading] = useState(true);+ const [loadingMore, setLoadingMore] = useState(false);+ const [membersById, setMembersById] = useState<+ Record<string, UserSelectGroupMembers>+ >({});const [loadingGroups, setLoadingGroups] = useState<Record<string, boolean>>({});- const [fetchedMembers, setFetchedMembers] = useState<Record<string, User[]>>(- {}+ const [expandedUids, setExpandedUids] = useState<Set<string>>(new Set());+ const [searchResults, setSearchResults] = useState<{+ groups: UserSelectGroup[];+ users: User[];+ } | null>(null);+ const [searching, setSearching] = useState(false);+ const [errors, setErrors] = useState<{ message: string } | undefined>(+ undefined);- const searchCache = useRef<Record<string, User[]>>({});/* Input */const [controlledValue, setControlledValue] = useState("");- /* Output */- const [filteredOptionGroups, setFilteredOptionGroups] = useState<- OptionGroup[]- >([]);-/* Focus */const [focusedId, setFocusedId] = useState<string | null>(null);@@ -109,166 +122,245 @@ export default function useUserSelect(props: UserSelectProps) {: {});- // Convert the tree from the server into a format that is easier to work with- const optionGroups = useMemo<OptionGroup[]>(() => {- const makeGroupItems = (- group: Group,- groupId: string- ): IndividualOrGroup[] => {- const result: IndividualOrGroup[] = [];-- if (!innerProps.usersOnly) {- result.push({- ...group.data,- uid: getOptionId(groupId, group.data.id),- label: group.data.name || "",- children: group.children+ /* Data fetching */++ const loadPage = useCallback(+ async (offset: number, append: boolean) => {+ const companyId = getCompanyId();+ const type = innerProps.type ?? null;+ if (append) {+ setLoadingMore(true);+ } else {+ setInitialLoading(true);+ }+ try {+ const data = await cachedApiQuery<{+ groups: UserSelectGroup[];+ hasMore: boolean;+ }>(+ userSelectGroupsQuery(companyId, type, offset),+ path.to.api.userSelectGroups(innerProps.type, offset, PAGE_SIZE)+ );+ setTopLevelGroups((prev) => {+ const base = append ? prev : [];+ const seen = new Set(base.map((g) => g.id));+ return base.concat(data.groups.filter((g) => !seen.has(g.id)));});+ setHasMore(data.hasMore);+ setErrors(undefined);+ } catch (err) {+ logger.error("Failed to load groups", { error: err });+ setErrors({ message: "Failed to load groups" });+ } finally {+ if (append) {+ setLoadingMore(false);+ } else {+ setInitialLoading(false);+ }+ }+ },+ [innerProps.type]+ );- const subgroups = group.children.map((subgroup) => ({- ...subgroup.data,- uid: getOptionId(groupId, subgroup.data.id),- label: subgroup.data.name || "",- children: subgroup.children- }));+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset + first page on type change only+ useEffect(() => {+ setTopLevelGroups([]);+ setHasMore(false);+ setMembersById({});+ setExpandedUids(new Set());+ setSearchResults(null);+ loadPage(0, false);+ }, [innerProps.type]);- result.push(...subgroups);- }+ const loadMore = useCallback(() => {+ if (loadingMore || initialLoading || !hasMore) return;+ loadPage(topLevelGroups.length, true);+ }, [loadingMore, initialLoading, hasMore, topLevelGroups.length, loadPage]);- const users = (- fetchedMembers[group.data.id] ||- group.data.users ||- []- ).map((user) => {- return {- ...user,- uid: getOptionId(groupId, user.id),- label: user.fullName || ""- };- });+ const fetchMembers = useCallback(+ async (groupId: string): Promise<UserSelectGroupMembers | null> => {+ const companyId = getCompanyId();+ setLoadingGroups((prev) =>+ prev[groupId] ? prev : { ...prev, [groupId]: true }+ );+ try {+ const data = await cachedApiQuery<UserSelectGroupMembers>(+ userSelectMembersQuery(companyId, groupId),+ path.to.api.userSelectGroupMembers(groupId)+ );+ setMembersById((prev) => ({ ...prev, [groupId]: data }));+ return data;+ } catch (err) {+ logger.error("Failed to fetch group members", { error: err });+ return null;+ } finally {+ setLoadingGroups((prev) => ({ ...prev, [groupId]: false }));+ }+ },+ []+ );- result.push(...users);+ const prefetchGroup = useCallback(+ (groupId: string) => {+ if (!groupId || membersById[groupId] || loadingGroups[groupId]) return;+ void fetchMembers(groupId);+ },+ [membersById, loadingGroups, fetchMembers]+ );- return result;- };+ /* View model — the lazily-built tree (or flat search results) */- return !groupsFetcher.data || !groupsFetcher.data.groups- ? []- : groupsFetcher.data.groups.reduce<OptionGroup[]>((acc, group) => {- if (- !innerProps.usersOnly ||- (group.data.users && group.data.users.length) ||- (fetchedMembers[group.data.id] &&- fetchedMembers[group.data.id].length)- ) {- const uid = getGroupId(instanceId, group.data.id);- return acc.concat({- uid,- expanded: false,- items: makeGroupItems(group as Group, uid),- name: group.data.name || ""- });- }- return acc;- }, []);- }, [groupsFetcher.data, innerProps.usersOnly, instanceId, fetchedMembers]);+ const viewModel = useMemo<UserSelectViewModel>(() => {+ uidToGroupId.current = {};+ const { usersOnly, queryFilters } = innerProps;+ const allowedIds = queryFilters?.allowedIds;- /* Pre-populate controlled component after data loads */- useEffect(() => {- if (innerProps.value && optionGroups && optionGroups.length > 0) {- const flattened = optionGroups.reduce<IndividualOrGroup[]>(- (acc, group) => acc.concat(group.items),- []- );- const values = Array.isArray(innerProps.value)- ? innerProps.value- : [innerProps.value];-- const newSelections: SelectionItemsById = {};- const missingUserIds: string[] = [];-- values.forEach((val) => {- if (!selectionItemsById[val]) {- const found = flattened.find((item) => item.id === val);- if (found) {- newSelections[val] = found;- } else if (typeof val === "string" && !val.startsWith("group_")) {- missingUserIds.push(val);- }- }- });+ const toUserOption = (user: User, parentUid: string): UserWithOptions => ({+ ...user,+ uid: getOptionId(parentUid, user.id),+ label: user.fullName || ""+ });- if (Object.keys(newSelections).length > 0) {- setSelectionItemsById((prev) => ({ ...prev, ...newSelections }));- }+ const q = controlledValue.trim();++ if (q.length >= 2 && searchResults) {+ const groups: SelectionGroupWithOptions[] = usersOnly+ ? []+ : searchResults.groups.map((g) => ({+ ...g,+ users: [],+ memberCount: g.userCount,+ uid: getOptionId("search", g.id),+ label: g.name || ""+ }));+ const users = searchResults.users+ .filter((u) => !allowedIds?.length || allowedIds.includes(u.id))+ .map((u) => toUserOption(u, "search"));+ return { mode: "search", groups, users, searching };+ }- if (missingUserIds.length > 0) {- const fetchMissing = async () => {- try {- const res = await fetch(path.to.api.usersBatch(missingUserIds));- const data = await res.json();- if (data.users && data.users.length > 0) {- setSelectionItemsById((prev) => {- const next = { ...prev };- data.users.forEach((u: User) => {- if (!next[u.id]) {- next[u.id] = {- ...u,- uid: getOptionId("preselected", u.id),- label: u.fullName || ""- };- }- });- return next;- });- }- } catch (err) {- logger.error("Failed to fetch preselected users", { error: err });- }+ const isVisibleGroup = (g: UserSelectGroup) =>+ !usersOnly || g.userCount + g.groupCount > 0;++ const buildNode = (+ group: UserSelectGroup,+ parentUid: string,+ ancestry: Set<string>+ ): GroupNode => {+ const uid = getGroupUid(parentUid, group.id);+ uidToGroupId.current[uid] = group.id;+ const expanded = expandedUids.has(uid);+ const raw = membersById[group.id];+ let members: GroupNode["members"] = null;+ if (raw) {+ const nextAncestry = new Set(ancestry).add(group.id);+ members = {+ groups: raw.groups+ .filter((cg) => !nextAncestry.has(cg.id))+ .filter(isVisibleGroup)+ .map((cg) => buildNode(cg, uid, nextAncestry)),+ users: raw.users+ .filter((u) => !allowedIds?.length || allowedIds.includes(u.id))+ .map((u) => toUserOption(u, uid))};- fetchMissing();}+ return {+ uid,+ group,+ expanded,+ loading: !!loadingGroups[group.id],+ members+ };+ };++ let top = topLevelGroups.filter(isVisibleGroup);+ if (q.length === 1) {+ top = top.filter((g) => stringContainsTerm(g.name || "", q));}- }, [optionGroups, innerProps.value, selectionItemsById]);-- const makeFilteredOptionGroups = useCallback(- (query?: string): OptionGroup[] =>- optionGroups.reduce((acc, group) => {- if (query?.trim()) {- const matches = group.items.filter((item) =>- stringContainsTerm(item.label, query)- );- if (matches && matches.length) {- return acc.concat({- ...group,- expanded: true,- items: matches- });- } else {- return acc;- }- } else {- return acc.concat(group);- }- }, [] as OptionGroup[]),- [optionGroups]- );- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ return {+ mode: "browse",+ nodes: top.map((g) => buildNode(g, instanceId, new Set())),+ hasMore,+ loadingMore+ };+ }, [+ innerProps,+ controlledValue,+ searchResults,+ searching,+ topLevelGroups,+ membersById,+ expandedUids,+ loadingGroups,+ hasMore,+ loadingMore,+ instanceId+ ]);++ /* Resolve preselected ids (users AND groups) not yet known locally */+useEffect(() => {- // Preserve each group's expanded state so it doesn't collapse when its- // lazily-fetched members arrive.- setFilteredOptionGroups((previousGroups) => {- const expandedByUid = new Map(- previousGroups.map((group) => [group.uid, group.expanded])- );- return makeFilteredOptionGroups().map((group) =>- expandedByUid.has(group.uid)- ? { ...group, expanded: expandedByUid.get(group.uid)! }- : group- );+ const value = innerProps.value;+ if (value === undefined || value === null) return;+ const values = (Array.isArray(value) ? value : [value]).filter(Boolean);+ const missing = values.filter(+ (val) => !selectionItemsById[val] && !resolveRequested.current.has(val)+ );+ if (missing.length === 0) return;+ missing.forEach((val) => {+ resolveRequested.current.add(val);});- }, [optionGroups, makeFilteredOptionGroups, setFilteredOptionGroups]);++ const companyId = getCompanyId();+ cachedApiQuery<{+ users: User[];+ groups: { id: string; name: string }[];+ }>(+ userSelectResolveQuery(companyId, missing),+ path.to.api.userSelectResolve(missing)+ )+ .then((data) => {+ setSelectionItemsById((prev) => {+ let changed = false;+ const next = { ...prev };+ data.users.forEach((u) => {+ if (!next[u.id]) {+ next[u.id] = {+ ...u,+ uid: getOptionId("preselected", u.id),+ label: u.fullName || ""+ };+ changed = true;+ }+ });+ data.groups.forEach((g) => {+ if (!next[g.id]) {+ next[g.id] = {+ id: g.id,+ name: g.name,+ isEmployeeTypeGroup: false,+ isCustomerOrgGroup: false,+ isCustomerTypeGroup: false,+ isSupplierOrgGroup: false,+ isSupplierTypeGroup: false,+ userCount: 0,+ groupCount: 0,+ users: [],+ memberCount: 0,+ uid: getOptionId("preselected", g.id),+ label: g.name || ""+ };+ changed = true;+ }+ });+ return changed ? next : prev;+ });+ })+ .catch((err) =>+ logger.error("Failed to resolve preselected values", { error: err })+ );+ }, [innerProps.value, selectionItemsById]);/* Event Handlers */@@ -292,11 +384,10 @@ export default function useUserSelect(props: UserSelectProps) {}}, []);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst clear = useCallback(() => {- setFilteredOptionGroups(makeFilteredOptionGroups());setControlledValue("");- }, [makeFilteredOptionGroups, setControlledValue, setFilteredOptionGroups]);+ setSearchResults(null);+ }, []);const resetFocus = useCallback(() => {setFocusedId(null);@@ -306,64 +397,30 @@ export default function useUserSelect(props: UserSelectProps) {}}, [focusInput]);- const prefetchGroup = useCallback(- (uid: string) => {- const groupId = uid.split("_")[1];- if (groupId && !fetchedMembers[groupId] && !loadingGroups[groupId]) {- setLoadingGroups((prev) => ({ ...prev, [groupId]: true }));- fetch(path.to.api.groupMembers(groupId))- .then((res) => res.json())- .then((data) => {- if (data.users) {- let users = data.users as User[];- const { queryFilters } = innerProps;- if (queryFilters?.allowedIds?.length) {- users = users.filter((u) =>- queryFilters.allowedIds!.includes(u.id)- );- }- setFetchedMembers((prev) => ({ ...prev, [groupId]: users }));- }- })- .catch((err) =>- logger.error("Failed to prefetch group", { error: err })- )- .finally(() => {- setLoadingGroups((prev) => ({ ...prev, [groupId]: false }));- });- }- },- [fetchedMembers, loadingGroups, innerProps]- );-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onGroupExpand = useCallback((uid: string) => {- setFilteredOptionGroups((previousGroups) =>- previousGroups.map((group) =>- group.uid === uid ? { ...group, expanded: true } : group- )- );- prefetchGroup(uid);+ setExpandedUids((prev) => {+ const next = new Set(prev);+ next.add(uid);+ return next;+ });+ const groupId = uidToGroupId.current[uid];+ if (groupId) prefetchGroup(groupId);},- [setFilteredOptionGroups, prefetchGroup]+ [prefetchGroup]);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- const onGroupCollapse = useCallback(- (uid: string) =>- setFilteredOptionGroups((previousGroups) =>- previousGroups.map((group) =>- group.uid === uid ? { ...group, expanded: false } : group- )- ),- [setFilteredOptionGroups]- );+ const onGroupCollapse = useCallback((uid: string) => {+ setExpandedUids((prev) => {+ const next = new Set(prev);+ next.delete(uid);+ return next;+ });+ }, []);const isExpanded = useCallback(- (uid: string) =>- filteredOptionGroups.some((g) => g.uid === uid && g.expanded),- [filteredOptionGroups]+ (uid: string) => expandedUids.has(uid),+ [expandedUids]);const getFirstNode = useCallback(() => {@@ -419,7 +476,7 @@ export default function useUserSelect(props: UserSelectProps) {);const hasChildren = useCallback((id: string) => {- return focusableNodes.current[id].expandable ?? false;+ return focusableNodes.current[id]?.expandable ?? false;}, []);const scrollTo = useCallback((elementId: string, delay: boolean) => {@@ -437,15 +494,36 @@ export default function useUserSelect(props: UserSelectProps) {}, []);const getSelectionById = useCallback(- (uid: string) => {- for (const group of filteredOptionGroups) {- const result = group.items.find((item) => item.uid === uid);- if (result) return result;+ (uid: string): IndividualOrGroup | undefined => {+ if (viewModel.mode === "search") {+ return (+ viewModel.groups.find((g) => g.uid === uid) ??+ viewModel.users.find((u) => u.uid === uid)+ );}- return undefined;+ let found: IndividualOrGroup | undefined;+ const walk = (nodes: GroupNode[]) => {+ for (const node of nodes) {+ if (found) return;+ if (node.uid === uid) {+ found = toGroupSelection(node.group, node.uid);+ return;+ }+ if (node.members) {+ const user = node.members.users.find((u) => u.uid === uid);+ if (user) {+ found = user;+ return;+ }+ walk(node.members.groups);+ }+ }+ };+ walk(viewModel.nodes);+ return found;},- [filteredOptionGroups]+ [viewModel]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration@@ -490,78 +568,45 @@ export default function useUserSelect(props: UserSelectProps) {]);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst debouncedInputChange = useMemo(() => {- const { queryFilters } = innerProps;+ const { queryFilters, type } = innerProps;return debounce(async (search: string) => {const q = search.trim();- if (q.length >= 2) {- const cacheKey = `${q}|${queryFilters?.excludeSelf ?? ""}|${queryFilters?.allowedIds?.join(",") ?? ""}`;- if (searchCache.current[cacheKey]) {- const searchResults = searchCache.current[cacheKey].map(- (user: User) => ({- ...user,- uid: getOptionId("search", user.id),- label: user.fullName || ""- })- );-- setFilteredOptionGroups([- {- uid: "search_results",- expanded: true,- items: searchResults,- name: "Search Results"- }- ]);- resetFocus();- return;- }+ if (q.length < 2) {+ setSearchResults(null);+ setSearching(false);+ resetFocus();+ return;+ }- try {- let searchUrl = path.to.api.usersSearch(q);- if (queryFilters?.excludeSelf) {- searchUrl += "&excludeSelf=true";- }- if (queryFilters?.allowedIds?.length) {- searchUrl += `&allowedIds=${queryFilters.allowedIds.join(",")}`;- }+ const companyId = getCompanyId();+ const filtersKey = `${queryFilters?.excludeSelf ?? ""}|${queryFilters?.allowedIds?.join(",") ?? ""}`;+ let searchUrl = path.to.api.userSelectSearch(q, type);+ if (queryFilters?.excludeSelf) {+ searchUrl += "&excludeSelf=true";+ }+ if (queryFilters?.allowedIds?.length) {+ searchUrl += `&allowedIds=${queryFilters.allowedIds.join(",")}`;+ }- const res = await fetch(searchUrl);- const data = await res.json();- if (data.users && data.users.length > 0) {- searchCache.current[cacheKey] = data.users;- const searchResults = data.users.map((user: User) => ({- ...user,- uid: getOptionId("search", user.id),- label: user.fullName || ""- }));-- setFilteredOptionGroups([- {- uid: "search_results",- expanded: true,- items: searchResults,- name: "Search Results"- }- ]);- } else {- setFilteredOptionGroups([]);- }- } catch (e) {- logger.error("Failed to search users", { error: e });- }- } else {- setFilteredOptionGroups(makeFilteredOptionGroups(search));+ setSearching(true);+ try {+ const data = await cachedApiQuery<{+ groups: UserSelectGroup[];+ users: User[];+ }>(+ userSelectSearchQuery(companyId, type ?? null, q, filtersKey),+ searchUrl+ );+ setSearchResults(data);+ } catch (e) {+ logger.error("Failed to search users", { error: e });+ } finally {+ setSearching(false);+ resetFocus();}- resetFocus();}, 240);- }, [- makeFilteredOptionGroups,- resetFocus,- setFilteredOptionGroups,- innerProps- ]);+ }, [resetFocus, innerProps]);const onInputFocus = useCallback(() => {dropdown.onOpen();@@ -641,6 +686,9 @@ export default function useUserSelect(props: UserSelectProps) {(selectionItem: IndividualOrGroup) => {if (selectionItem === undefined) return;const { id } = selectionItem;+ // Keep the hydration effect from re-resolving an id the user just+ // removed while the wrapper's value prop is still one render behind.+ resolveRequested.current.add(id);setSelectionItemsById((previousSelections) => {if (id in previousSelections) {// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration@@ -718,15 +766,34 @@ export default function useUserSelect(props: UserSelectProps) {]);+ /**+ * Replace a selected group with its direct members (users + child groups).+ * Members are fetched on demand if not already loaded.+ */// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onExplode = useCallback((selectionItem: IndividualOrGroup) => {if (!("users" in selectionItem)) return;+ const { id } = selectionItem;+ const { queryFilters } = innerProps;++ // The wrapper's value prop lags one render behind the onChange below;+ // without this the hydration effect resolves the exploded group id and+ // re-adds it as a ghost chip.+ resolveRequested.current.add(id);++ void (async () => {+ const members = membersById[id] ?? (await fetchMembers(id));+ if (!members) return;- const { id, users, children } = selectionItem;+ const allowedIds = queryFilters?.allowedIds;+ const users = members.users.filter(+ (u) => !allowedIds?.length || allowedIds.includes(u.id)+ );++ setSelectionItemsById((prevSelectionItems) => {+ if (!(id in prevSelectionItems)) return prevSelectionItems;- setSelectionItemsById((prevSelectionItems) => {- if (id in prevSelectionItems) {// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migrationconst { [id]: removed, ...newSelectionItems } = prevSelectionItems;@@ -738,22 +805,19 @@ export default function useUserSelect(props: UserSelectProps) {};});- children?.forEach((group) => {- newSelectionItems[group.data.id] = {- ...group.data,- uid: getOptionId(id, group.data.id),- label: group.data.name || ""- };+ members.groups.forEach((group) => {+ newSelectionItems[group.id] = toGroupSelection(+ group,+ getOptionId(id, group.id)+ );});onChange(Object.values(newSelectionItems));return newSelectionItems;- }-- return prevSelectionItems;- });+ });+ })();},- [onChange, setSelectionItemsById]+ [membersById, fetchMembers, innerProps, onChange, setSelectionItemsById]);const onKeyDown = useCallback(@@ -765,12 +829,12 @@ export default function useUserSelect(props: UserSelectProps) {switch (event.key) {case "ArrowLeft":if (focusedId) {- if (hasParent(focusedId)) {+ if (hasChildren(focusedId) && isExpanded(focusedId)) {+ onGroupCollapse(focusedId);+ } else if (hasParent(focusedId)) {const { parentId } = focusableNodes.current[focusedId];onGroupCollapse(parentId!);setFocus(parentId!);- } else {- onGroupCollapse(focusedId);}break;} else {@@ -794,10 +858,19 @@ export default function useUserSelect(props: UserSelectProps) {commit();return;case "Enter":- if (focusedId && hasParent(focusedId)) {- onSelect(getSelectionById(focusedId));- clear();- commit();+ if (focusedId) {+ if (hasChildren(focusedId) && innerProps.usersOnly) {+ // groups aren't selectable in usersOnly mode — toggle expansion+ if (isExpanded(focusedId)) {+ onGroupCollapse(focusedId);+ } else {+ onGroupExpand(focusedId);+ }+ } else {+ onSelect(getSelectionById(focusedId));+ clear();+ commit();+ }break;}break;@@ -810,7 +883,13 @@ export default function useUserSelect(props: UserSelectProps) {break;case " ": // spaceif (focusedId) {- if (hasParent(focusedId)) {+ if (hasChildren(focusedId) && innerProps.usersOnly) {+ if (isExpanded(focusedId)) {+ onGroupCollapse(focusedId);+ } else {+ onGroupExpand(focusedId);+ }+ } else {onToggle(getSelectionById(focusedId));}break;@@ -849,6 +928,7 @@ export default function useUserSelect(props: UserSelectProps) {hasChildren,isExpanded,innerProps.disabled,+ innerProps.usersOnly,clear,onGroupCollapse,onGroupExpand,@@ -902,9 +982,9 @@ export default function useUserSelect(props: UserSelectProps) {return {aria,- groups: filteredOptionGroups,- errors: groupsFetcher.data?.errors,- loading: groupsFetcher.state === "loading",+ viewModel,+ errors,+ loading: initialLoading,loadingGroups,selectionItemsById,// focus@@ -924,6 +1004,8 @@ export default function useUserSelect(props: UserSelectProps) {buttonRef,focusableNodes},+ // pagination+ loadMore,// event handlersonClearInput,onKeyDown,@@ -947,8 +1029,22 @@ function getOptionId(groupId: string, optionId: string) {return `${groupId}_${optionId}_option`;}-function getGroupId(instanceId: string, groupId: string) {- return `${instanceId}_${groupId}_group`;+function getGroupUid(parentUid: string, groupId: string) {+ return `${parentUid}_${groupId}_group`;+}++/** Build the selection item for a group (users stays [] until exploded). */+function toGroupSelection(+ group: UserSelectGroup,+ uid: string+): SelectionGroupWithOptions {+ return {+ ...group,+ users: [],+ memberCount: group.userCount + group.groupCount,+ uid,+ label: group.name || ""+ };}function checked(item: IndividualOrGroup): IndividualOrGroup {@@ -959,10 +1055,7 @@ function checked(item: IndividualOrGroup): IndividualOrGroup {}export function isGroup(item: IndividualOrGroup) {- return (- ("users" in item && item.users?.length > 0) ||- ("children" in item && item?.children?.length)- );+ return "users" in item;}function toggleChecked(item: IndividualOrGroup): IndividualOrGroup {diff --git a/apps/erp/app/modules/users/types.ts b/apps/erp/app/modules/users/types.tsindex 44e82229a6..691fe0460c 100644--- a/apps/erp/app/modules/users/types.ts+++ b/apps/erp/app/modules/users/types.ts@@ -48,6 +48,24 @@ export type Group = {children: Group[];};+export type UserSelectGroup = {+ id: string;+ name: string;+ isEmployeeTypeGroup: boolean;+ isCustomerOrgGroup: boolean;+ isCustomerTypeGroup: boolean;+ isSupplierOrgGroup: boolean;+ isSupplierTypeGroup: boolean;+ userCount: number;+ groupCount: number;+ isRoot?: boolean; // present on list results, absent on member child groups+};++export type UserSelectGroupMembers = {+ groups: UserSelectGroup[];+ users: User[];+};+export type CompanyPermission = {view: boolean;create: boolean;diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex f4ee02a9ba..8f5268ecdb 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -1,12 +1,12 @@import type { Database } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";import { getLogger } from "@carbon/logger";-import type { SupabaseClient } from "@supabase/supabase-js";+import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import type { GenericQueryFilters } from "~/utils/query";import { setGenericQueryFilters } from "~/utils/query";import { capitalize } from "~/utils/string";import { sanitize } from "~/utils/supabase";-import type { CompanyPermission } from "./types";+import type { CompanyPermission, UserSelectGroupMembers } from "./types";const logger = getLogger("erp", "users");@@ -261,6 +261,105 @@ export async function getGroupEmails(return getUserEmails(client, userIdsResult.data);}+export async function getUserSelectGroups(+ client: SupabaseClient<Database>,+ companyId: string,+ args: { type?: string; search?: string; limit: number; offset: number }+) {+ return client.rpc("get_user_select_groups", {+ p_company_id: companyId,+ p_limit: args.limit,+ p_offset: args.offset,+ ...(args.type ? { p_type: args.type } : {}),+ ...(args.search ? { p_search: args.search } : {})+ });+}++export async function getUserSelectGroupMembers(+ client: SupabaseClient<Database>,+ companyId: string,+ groupId: string+): Promise<{+ data: UserSelectGroupMembers | null;+ error: PostgrestError | null;+}> {+ const result = await client.rpc("get_user_select_group_members", {+ p_company_id: companyId,+ p_group_id: groupId+ });+ return {+ data: result.data as unknown as UserSelectGroupMembers | null,+ error: result.error+ };+}++export async function searchUsersForSelect(+ client: SupabaseClient<Database>,+ companyId: string,+ args: {+ q: string;+ type?: string;+ excludeSelf?: boolean;+ allowedIds?: string[];+ userId: string;+ }+) {+ // Search exactly the population the user-select tree can reach: active+ // users who are members of this company's groups (the groupMembers view+ // joins active users only — same visibility rule as expanding a group),+ // filtered by the same type flags as get_user_select_groups. Rows repeat+ // per group membership — the caller dedupes by memberUserId.+ let query = client+ .from("groupMembers")+ .select("memberUserId, user")+ .eq("companyId", companyId)+ .not("memberUserId", "is", null)+ .ilike("user->>fullName", `%${args.q}%`)+ .limit(100);++ if (args.type === "customer") {+ query = query.or("isCustomerTypeGroup.eq.true,isCustomerOrgGroup.eq.true");+ } else if (args.type === "supplier") {+ query = query.or("isSupplierTypeGroup.eq.true,isSupplierOrgGroup.eq.true");+ } else {+ query = query+ .eq("isCustomerTypeGroup", false)+ .eq("isCustomerOrgGroup", false)+ .eq("isSupplierTypeGroup", false)+ .eq("isSupplierOrgGroup", false);+ }++ if (args.excludeSelf) {+ query = query.neq("memberUserId", args.userId);+ }++ if (args.allowedIds && args.allowedIds.length > 0) {+ query = query.in("memberUserId", args.allowedIds);+ }++ return query;+}++export async function resolveUserSelectIds(+ client: SupabaseClient<Database>,+ companyId: string,+ ids: string[]+) {+ const [users, groups] = await Promise.all([+ client+ .from("user")+ .select("id, firstName, lastName, fullName, email, avatarUrl")+ .in("id", ids),+ client+ .from("group")+ .select("id, name")+ .in("id", ids)+ .eq("companyId", companyId)+ .eq("isIdentityGroup", false)+ ]);+ return { users, groups };+}+export async function getPermissionsByEmployeeType(client: SupabaseClient<Database>,employeeTypeId: stringdiff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 41490067ee..bedb749e7a 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-07-14T19:38:37.774Z",- "totalTools": 1327,+ "generated": "2026-07-14T22:27:32.390Z",+ "totalTools": 1331,"modules": 15,"tools": [{@@ -13884,7 +13884,7 @@"module": "items","classification": "WRITE","description": "upsert method material",- "paramCount": 1,+ "paramCount": 4,"serviceParams": ["client","methodMaterial"@@ -13897,10 +13897,22 @@"schema": {"type": "object","properties": {- "methodMaterial": {}+ "id": {+ "type": "string"+ },+ "makeMethodId": {+ "type": "string"+ },+ "order": {+ "type": "number"+ },+ "itemType": {+ "type": "string"+ }},"required": [- "methodMaterial"+ "id",+ "makeMethodId"]}},@@ -40765,6 +40777,135 @@]}},+ {+ "name": "users_getUserSelectGroups",+ "module": "users",+ "classification": "READ",+ "description": "get user select groups",+ "paramCount": 4,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string"+ },+ "search": {+ "type": "string"+ },+ "limit": {+ "type": "number"+ },+ "offset": {+ "type": "number"+ }+ },+ "required": [+ "limit",+ "offset"+ ]+ }+ },+ {+ "name": "users_getUserSelectGroupMembers",+ "module": "users",+ "classification": "READ",+ "description": "get user select group members",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "groupId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "groupId": {+ "type": "string"+ }+ },+ "required": [+ "groupId"+ ]+ }+ },+ {+ "name": "users_searchUsersForSelect",+ "module": "users",+ "classification": "READ",+ "description": "search users for select",+ "paramCount": 4,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "q": {+ "type": "string"+ },+ "type": {+ "type": "string"+ },+ "excludeSelf": {+ "type": "boolean"+ },+ "allowedIds": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "q"+ ]+ }+ },+ {+ "name": "users_resolveUserSelectIds",+ "module": "users",+ "classification": "WRITE",+ "description": "resolve user select ids",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "ids"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "ids"+ ]+ }+ },{"name": "users_getPermissionsByEmployeeType","module": "users",diff --git a/apps/erp/app/routes/api+/users.batch.tsx b/apps/erp/app/routes/api+/users.batch.tsxdeleted file mode 100644index 0e272c6406..0000000000--- a/apps/erp/app/routes/api+/users.batch.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type { LoaderFunctionArgs } from "react-router";-import { data } from "react-router";--export async function loader({ request }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, {- role: "employee"- });-- const url = new URL(request.url);- const idsParam = url.searchParams.get("ids");- if (!idsParam) return { users: [] };-- const ids = idsParam.split(",").filter(Boolean);-- if (ids.length === 0) return { users: [] };-- const query = await client- .from("user")- .select("id, firstName, lastName, fullName, email, avatarUrl")- .in("id", ids);-- if (query.error) {- return data(- { users: [], error: query.error },- await flash(request, error(query.error, "Failed to load users"))- );- }-- return { users: query.data ?? [] };-}diff --git a/apps/erp/app/routes/api+/users.groups.$groupId.members.tsx b/apps/erp/app/routes/api+/users.groups.$groupId.members.tsxdeleted file mode 100644index 47f5dc9444..0000000000--- a/apps/erp/app/routes/api+/users.groups.$groupId.members.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";-import { data } from "react-router";--export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- role: "employee"- });-- const { groupId } = params;- if (!groupId) {- throw new Response("Group ID is required", { status: 400 });- }-- // The `groups` view returns multiple rows per id for nested groups (members- // are identical), so take one row instead of erroring with `.single()`.- const query = await client- .from("groups")- .select("users")- .eq("id", groupId)- .eq("companyId", companyId)- .limit(1)- .maybeSingle();-- if (query.error) {- return data(- { users: [], error: query.error },- await flash(request, error(query.error, "Failed to load group members"))- );- }-- return { users: query.data?.users ?? [] };-}--export async function clientLoader({- params,- serverLoader-}: ClientLoaderFunctionArgs) {- const { groupId } = params;- if (!groupId) {- return await serverLoader<typeof loader>();- }-- const queryKey = ["groupMembers", groupId];- const cached =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (cached) {- return cached;- }-- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;-}-clientLoader.hydrate = true;diff --git a/apps/erp/app/routes/api+/users.groups.tsx b/apps/erp/app/routes/api+/users.groups.tsxdeleted file mode 100644index 62a43d39c1..0000000000--- a/apps/erp/app/routes/api+/users.groups.tsx+++ /dev/null@@ -1,84 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { arrayToTree } from "performant-array-to-tree";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";-import { data } from "react-router";-import type { Group } from "~/modules/users";-import { getCompanyId, groupsByTypeQuery } from "~/utils/react-query";--export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const type = searchParams.get("type");- const includeUsers = searchParams.get("include") === "users";-- const selectCols = includeUsers- ? "id, name, companyId, isEmployeeTypeGroup, isCustomerOrgGroup, isCustomerTypeGroup, isSupplierOrgGroup, isSupplierTypeGroup, parentId, users"- : "id, name, companyId, isEmployeeTypeGroup, isCustomerOrgGroup, isCustomerTypeGroup, isSupplierOrgGroup, isSupplierTypeGroup, parentId";-- const query = client- .from("groups")- .select(selectCols)- .eq("companyId", companyId);-- if (type === "employee") {- query.eq("isCustomerOrgGroup", false);- query.eq("isCustomerTypeGroup", false);- query.eq("isSupplierOrgGroup", false);- query.eq("isSupplierTypeGroup", false);- } else if (type === "customer") {- query.or("isCustomerTypeGroup.eq.true, isCustomerOrgGroup.eq.true");- } else if (type === "supplier") {- query.or("isSupplierTypeGroup.eq.true, isSupplierOrgGroup.eq.true");- }-- const groups = await query;-- if (groups.error) {- return data(- { groups: [], error: groups.error },- await flash(request, error(groups.error, "Failed to load groups"))- );- }-- return {- groups: arrayToTree(groups.data) as Group[]- };-}--export async function clientLoader({- request,- serverLoader-}: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const url = new URL(request.url);- const type = url.searchParams.get("type");-- const queryKey = groupsByTypeQuery(companyId, type).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;diff --git a/apps/erp/app/routes/api+/users.search.tsx b/apps/erp/app/routes/api+/users.search.tsxdeleted file mode 100644index c0d62b90ca..0000000000--- a/apps/erp/app/routes/api+/users.search.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import type { LoaderFunctionArgs } from "react-router";-import { data } from "react-router";--export async function loader({ request }: LoaderFunctionArgs) {- const { client, userId } = await requirePermissions(request, {- role: "employee"- });-- const url = new URL(request.url);- const q = url.searchParams.get("q")?.trim();-- if (!q || q.length < 2) {- return { users: [] };- }-- const excludeSelf = url.searchParams.get("excludeSelf") === "true";- const allowedIds = url.searchParams- .get("allowedIds")- ?.split(",")- .filter(Boolean);-- const query = client- .from("user")- .select("id, firstName, lastName, fullName, email, avatarUrl")- .eq("active", true)- .ilike("fullName", `%${q}%`)- .order("lastName")- .limit(20);-- if (excludeSelf) {- query.neq("id", userId);- }-- if (allowedIds && allowedIds.length > 0) {- query.in("id", allowedIds);- }-- const result = await query;-- if (result.error) {- return data(- { users: [], error: result.error },- await flash(request, error(result.error, "Failed to search users"))- );- }-- return { users: result.data ?? [] };-}diff --git a/apps/erp/app/routes/api+/users.select.groups.$groupId.emails.tsx b/apps/erp/app/routes/api+/users.select.groups.$groupId.emails.tsxnew file mode 100644index 0000000000..016243d7b7--- /dev/null+++ b/apps/erp/app/routes/api+/users.select.groups.$groupId.emails.tsx@@ -0,0 +1,40 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getGroupEmails } from "~/modules/users";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ role: "employee"+ });++ const { groupId } = params;+ if (!groupId) {+ return { emails: [] };+ }++ // users_for_groups (SECURITY DEFINER) has no tenant check of its own —+ // verify the group belongs to the caller's company first.+ const group = await client+ .from("group")+ .select("id")+ .eq("id", groupId)+ .eq("companyId", companyId)+ .maybeSingle();++ if (group.error) {+ return data(+ { emails: [], error: group.error },+ await flash(request, error(group.error, "Failed to load group emails"))+ );+ }++ if (!group.data) {+ return { emails: [] };+ }++ const emails = await getGroupEmails(client, [groupId]);+ return { emails: [...new Set(emails)] };+}diff --git a/apps/erp/app/routes/api+/users.select.groups.$groupId.members.tsx b/apps/erp/app/routes/api+/users.select.groups.$groupId.members.tsxnew file mode 100644index 0000000000..8eb2434f7e--- /dev/null+++ b/apps/erp/app/routes/api+/users.select.groups.$groupId.members.tsx@@ -0,0 +1,37 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getUserSelectGroupMembers } from "~/modules/users";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ role: "employee"+ });++ const { groupId } = params;+ if (!groupId) {+ return data(+ { groups: [], users: [] },+ await flash(+ request,+ error(new Error("groupId is required"), "Group id is required")+ )+ );+ }++ const result = await getUserSelectGroupMembers(client, companyId, groupId);++ if (result.error) {+ return data(+ { groups: [], users: [], error: result.error },+ await flash(request, error(result.error, "Failed to load group members"))+ );+ }++ return {+ groups: result.data?.groups ?? [],+ users: result.data?.users ?? []+ };+}diff --git a/apps/erp/app/routes/api+/users.select.groups.tsx b/apps/erp/app/routes/api+/users.select.groups.tsxnew file mode 100644index 0000000000..0a89e3e434--- /dev/null+++ b/apps/erp/app/routes/api+/users.select.groups.tsx@@ -0,0 +1,39 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getUserSelectGroups } from "~/modules/users";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ role: "employee"+ });++ const url = new URL(request.url);+ const type = url.searchParams.get("type") || undefined;+ const offset = Math.max(0, Number(url.searchParams.get("offset")) || 0);+ const limit = Math.min(+ 100,+ Math.max(1, Number(url.searchParams.get("limit")) || 25)+ );++ const result = await getUserSelectGroups(client, companyId, {+ type,+ limit: limit + 1, // fetch one extra row to compute hasMore+ offset+ });++ if (result.error) {+ return data(+ { groups: [], hasMore: false, error: result.error },+ await flash(request, error(result.error, "Failed to load groups"))+ );+ }++ const rows = result.data ?? [];+ return {+ groups: rows.slice(0, limit),+ hasMore: rows.length > limit+ };+}diff --git a/apps/erp/app/routes/api+/users.select.resolve.tsx b/apps/erp/app/routes/api+/users.select.resolve.tsxnew file mode 100644index 0000000000..8ba43a9e22--- /dev/null+++ b/apps/erp/app/routes/api+/users.select.resolve.tsx@@ -0,0 +1,33 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { resolveUserSelectIds } from "~/modules/users";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ role: "employee"+ });++ const url = new URL(request.url);+ const ids = [+ ...new Set((url.searchParams.get("ids") ?? "").split(",").filter(Boolean))+ ].slice(0, 200);++ if (ids.length === 0) {+ return { users: [], groups: [] };+ }++ const { users, groups } = await resolveUserSelectIds(client, companyId, ids);++ if (users.error || groups.error) {+ const firstError = users.error ?? groups.error;+ return data(+ { users: [], groups: [], error: firstError },+ await flash(request, error(firstError, "Failed to resolve selections"))+ );+ }++ return { users: users.data ?? [], groups: groups.data ?? [] };+}diff --git a/apps/erp/app/routes/api+/users.select.search.tsx b/apps/erp/app/routes/api+/users.select.search.tsxnew file mode 100644index 0000000000..1ebb0ffb72--- /dev/null+++ b/apps/erp/app/routes/api+/users.select.search.tsx@@ -0,0 +1,87 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { getUserSelectGroups, searchUsersForSelect } from "~/modules/users";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ role: "employee"+ });++ const url = new URL(request.url);+ const q = url.searchParams.get("q")?.trim();++ if (!q || q.length < 2) {+ return { groups: [], users: [] };+ }++ const type = url.searchParams.get("type") || undefined;+ const excludeSelf = url.searchParams.get("excludeSelf") === "true";+ const allowedIds = url.searchParams+ .get("allowedIds")+ ?.split(",")+ .filter(Boolean);++ const [groupsResult, usersResult] = await Promise.all([+ getUserSelectGroups(client, companyId, {+ type,+ search: q,+ limit: 10,+ offset: 0+ }),+ searchUsersForSelect(client, companyId, {+ q,+ type,+ excludeSelf,+ allowedIds,+ userId+ })+ ]);++ if (groupsResult.error || usersResult.error) {+ const firstError = groupsResult.error ?? usersResult.error;+ return data(+ { groups: [], users: [], error: firstError },+ await flash(request, error(firstError, "Failed to search users"))+ );+ }++ // groupMembers rows repeat per membership and carry the user as jsonb+ const seen = new Set<string>();+ const users: {+ id: string;+ firstName: string;+ lastName: string;+ fullName: string | null;+ email: string;+ avatarUrl: string | null;+ }[] = [];+ for (const row of usersResult.data ?? []) {+ const user = row.user as {+ id: string;+ firstName: string;+ lastName: string;+ fullName: string | null;+ email: string;+ avatarUrl: string | null;+ } | null;+ if (!user || !row.memberUserId || seen.has(row.memberUserId)) continue;+ seen.add(row.memberUserId);+ users.push({+ id: user.id,+ firstName: user.firstName,+ lastName: user.lastName,+ fullName: user.fullName,+ email: user.email,+ avatarUrl: user.avatarUrl+ });+ }+ users.sort((a, b) => (a.lastName ?? "").localeCompare(b.lastName ?? ""));++ return {+ groups: groupsResult.data ?? [],+ users: users.slice(0, 20)+ };+}diff --git a/apps/erp/app/routes/x+/users+/customers.new.tsx b/apps/erp/app/routes/x+/users+/customers.new.tsxindex 3e3160fca0..138a2878ec 100644--- a/apps/erp/app/routes/x+/users+/customers.new.tsx+++ b/apps/erp/app/routes/x+/users+/customers.new.tsx@@ -13,7 +13,10 @@ import { sendEmail } from "@carbon/lib/resend.server";import { getLogger } from "@carbon/logger";import { render } from "@react-email/components";import { nanoid } from "nanoid";-import type { ActionFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";import { redirect } from "react-router";import {CreateCustomerModal,@@ -21,6 +24,7 @@ import {} from "~/modules/users";import { createCustomerAccount } from "~/modules/users/users.server";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";const logger = getLogger("erp", "customers-new");@@ -107,6 +111,11 @@ export async function action({ request }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function () {return <CreateCustomerModal />;}diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsxindex 18f95a455a..b95ae322b5 100644--- a/apps/erp/app/routes/x+/users+/deactivate.tsx+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx@@ -4,9 +4,13 @@ import { flash } from "@carbon/auth/session.server";import { deactivateUser } from "@carbon/auth/users.server";import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";-import type { ActionFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";import { redirect } from "react-router";import { deactivateUsersValidator } from "~/modules/users";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {@@ -62,3 +66,8 @@ export async function action({ request }: ActionFunctionArgs) {}}}++export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}diff --git a/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx b/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsxindex f7111c3b60..4b3dbc467b 100644--- a/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx@@ -2,7 +2,11 @@ import { assertIsPost, error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";import { data, redirect, useLoaderData } from "react-router";import {EmployeeTypeForm,@@ -15,6 +19,7 @@ import {} from "~/modules/users";import { makeCompanyPermissionsFromEmployeeType } from "~/modules/users/users.server";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -110,6 +115,11 @@ export async function action({ request }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function EditEmployeeTypesRoute() {const { employeeType, employeeTypePermissions } =useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx b/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsxindex 9f43a1dc7c..e5b183a88a 100644--- a/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx@@ -2,11 +2,16 @@ import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { useLingui } from "@lingui/react/macro";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";import { redirect, useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteEmployeeType, getEmployeeType } from "~/modules/users";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -67,6 +72,11 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function DeleteEmployeeTypeRoute() {const { employeeTypeId } = useParams();const { employeeType } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employee-types.new.tsx b/apps/erp/app/routes/x+/users+/employee-types.new.tsxindex 39d59db03f..b84f9440db 100644--- a/apps/erp/app/routes/x+/users+/employee-types.new.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.new.tsx@@ -2,7 +2,11 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";import { data, redirect, useLoaderData } from "react-router";import type { CompanyPermission } from "~/modules/users";import {@@ -15,6 +19,7 @@ import {} from "~/modules/users";import { makeEmptyPermissionsFromModules } from "~/modules/users/users.server";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -116,6 +121,11 @@ export async function action({ request }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function NewEmployeeTypesRoute() {const { permissions } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsxindex d10ed9cadc..f15efac3ab 100644--- a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx+++ b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx@@ -4,7 +4,11 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import type { Json } from "@carbon/database";import { validationError, validator } from "@carbon/form";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";import { data, redirect, useLoaderData } from "react-router";import type { CompanyPermission } from "~/modules/users";import {@@ -22,6 +26,7 @@ import {updateEmployee} from "~/modules/users/users.server";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { companyId } = await requirePermissions(request, {@@ -133,6 +138,11 @@ export async function action({ request }: ActionFunctionArgs) {throw redirect(path.to.employeeAccounts, await flash(request, result));}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function UsersEmployeeRoute() {const { permissions, employee, employeeTypes, employeeTypePermissions } =useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employees.new.tsx b/apps/erp/app/routes/x+/users+/employees.new.tsxindex 334d99b7e6..e39ad4494b 100644--- a/apps/erp/app/routes/x+/users+/employees.new.tsx+++ b/apps/erp/app/routes/x+/users+/employees.new.tsx@@ -26,7 +26,7 @@ import {} from "~/modules/users";import { createEmployeeAccount } from "~/modules/users/users.server";import { path } from "~/utils/path";-import { getCompanyId } from "~/utils/react-query";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";const logger = getLogger("erp", "employees-new");@@ -128,13 +128,7 @@ export async function action({ request }: ActionFunctionArgs) {}export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- const companyId = getCompanyId();- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return queryKey[0] === "groupsByType" && queryKey[1] === companyId;- }- });+ invalidateUserSelectQueries(getCompanyId());return await serverAction();}diff --git a/apps/erp/app/routes/x+/users+/groups.$groupId.tsx b/apps/erp/app/routes/x+/users+/groups.$groupId.tsxindex 663a26d6ac..40d9c07486 100644--- a/apps/erp/app/routes/x+/users+/groups.$groupId.tsx+++ b/apps/erp/app/routes/x+/users+/groups.$groupId.tsx@@ -2,7 +2,11 @@ import { assertIsPost, error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";import { redirect, useLoaderData } from "react-router";import {GroupForm,@@ -12,6 +16,7 @@ import {upsertGroupMembers} from "~/modules/users";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -97,6 +102,11 @@ export async function action({ request }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function UsersGroupRoute() {const { group } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsx b/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsxindex 15ac1e6a88..7341609844 100644--- a/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsx+++ b/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsx@@ -2,11 +2,16 @@ import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { useLingui } from "@lingui/react/macro";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs,+ LoaderFunctionArgs+} from "react-router";import { redirect, useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteGroup, getGroup } from "~/modules/users";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -55,6 +60,11 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function DeleteEmployeeTypeRoute() {const { groupId } = useParams();const { group } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/groups.new.tsx b/apps/erp/app/routes/x+/users+/groups.new.tsxindex fa78053c04..b4cd766b45 100644--- a/apps/erp/app/routes/x+/users+/groups.new.tsx+++ b/apps/erp/app/routes/x+/users+/groups.new.tsx@@ -15,7 +15,7 @@ import {upsertGroupMembers} from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId } from "~/utils/react-query";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -73,13 +73,7 @@ export async function action({ request }: ActionFunctionArgs) {}export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- const companyId = getCompanyId();- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return queryKey[0] === "groupsByType" && queryKey[1] === companyId;- }- });+ invalidateUserSelectQueries(getCompanyId());return await serverAction();}diff --git a/apps/erp/app/routes/x+/users+/suppliers.new.tsx b/apps/erp/app/routes/x+/users+/suppliers.new.tsxindex bb29c71854..27908c177d 100644--- a/apps/erp/app/routes/x+/users+/suppliers.new.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.new.tsx@@ -13,7 +13,10 @@ import { sendEmail } from "@carbon/lib/resend.server";import { getLogger } from "@carbon/logger";import { render } from "@react-email/components";import { nanoid } from "nanoid";-import type { ActionFunctionArgs } from "react-router";+import type {+ ActionFunctionArgs,+ ClientActionFunctionArgs+} from "react-router";import { redirect } from "react-router";import {CreateSupplierModal,@@ -21,6 +24,7 @@ import {} from "~/modules/users";import { createSupplierAccount } from "~/modules/users/users.server";import { path } from "~/utils/path";+import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";const logger = getLogger("erp", "suppliers-new");@@ -107,6 +111,11 @@ export async function action({ request }: ActionFunctionArgs) {);}+export async function clientAction({ serverAction }: ClientActionFunctionArgs) {+ invalidateUserSelectQueries(getCompanyId());+ return await serverAction();+}+export default function () {return <CreateSupplierModal />;}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 6a36486002..8bef89b08e 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -59,16 +59,24 @@ export const path = {generatePath(`${api}/quality/inspection-document/${inspectionDocumentId}/balloon-analyze`),- groupsByType: (type?: string) =>- generatePath(`${api}/users/groups?type=${type}`),- groupsByTypeWithUsers: (type?: string) =>- generatePath(`${api}/users/groups?type=${type}&include=users`),- groupMembers: (groupId: string) =>- generatePath(`${api}/users/groups/${groupId}/members`),- usersSearch: (q: string) =>- generatePath(`${api}/users/search?q=${encodeURIComponent(q)}`),- usersBatch: (ids: string[]) =>- generatePath(`${api}/users/batch?ids=${ids.join(",")}`),+ userSelectGroups: (+ type: string | undefined,+ offset: number,+ limit = 25+ ) =>+ generatePath(+ `${api}/users/select/groups?type=${type ?? ""}&offset=${offset}&limit=${limit}`+ ),+ userSelectGroupMembers: (groupId: string) =>+ generatePath(`${api}/users/select/groups/${groupId}/members`),+ userSelectSearch: (q: string, type?: string) =>+ generatePath(+ `${api}/users/select/search?q=${encodeURIComponent(q)}&type=${type ?? ""}`+ ),+ userSelectResolve: (ids: string[]) =>+ generatePath(`${api}/users/select/resolve?ids=${ids.join(",")}`),+ userSelectGroupEmails: (groupId: string) =>+ generatePath(`${api}/users/select/groups/${groupId}/emails`),item: (type: string) => generatePath(`${api}/item/${type}`),itemCostRecalculate: (itemId: string) =>generatePath(`${api}/items/${itemId}/recalculate-cost`),diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsindex eb198bb93d..7748ed6c71 100644--- a/apps/erp/app/utils/react-query.ts+++ b/apps/erp/app/utils/react-query.ts@@ -181,14 +181,6 @@ export const workCentersQuery = (companyId: string | null) => ({staleTime: RefreshRate.Low});-export const groupsByTypeQuery = (- companyId: string | null,- type: string | null-) => ({- queryKey: ["groupsByType", companyId ?? "null", type ?? "null"],- staleTime: RefreshRate.Low-});-export const materialTypesQuery = (substanceId: string,formId: string,@@ -197,3 +189,99 @@ export const materialTypesQuery = (queryKey: ["materialTypes", substanceId, formId, companyId ?? "null"],staleTime: RefreshRate.Low});++export const userSelectGroupsQuery = (+ companyId: string | null,+ type: string | null,+ offset: number+) => ({+ queryKey: ["userSelectGroups", companyId ?? "null", type ?? "all", offset],+ staleTime: RefreshRate.Low+});++export const userSelectMembersQuery = (+ companyId: string | null,+ groupId: string+) => ({+ queryKey: ["userSelectMembers", companyId ?? "null", groupId],+ staleTime: RefreshRate.Low+});++export const userSelectSearchQuery = (+ companyId: string | null,+ type: string | null,+ q: string,+ filters: string+) => ({+ queryKey: [+ "userSelectSearch",+ companyId ?? "null",+ type ?? "all",+ q,+ filters+ ],+ staleTime: RefreshRate.High+});++export const userSelectResolveQuery = (+ companyId: string | null,+ ids: string[]+) => ({+ queryKey: [+ "userSelectResolve",+ companyId ?? "null",+ [...ids].sort().join(",")+ ],+ staleTime: RefreshRate.Low+});++export const groupEmailsQuery = (+ companyId: string | null,+ groupId: string+) => ({+ queryKey: ["groupEmails", companyId ?? "null", groupId],+ staleTime: RefreshRate.Low+});++const USER_SELECT_QUERY_PREFIXES = [+ "userSelectGroups",+ "userSelectMembers",+ "userSelectSearch",+ "userSelectResolve",+ "groupEmails"+];++/**+ * Read-through fetch against an API route, cached in window.clientCache.+ * fetchQuery dedupes concurrent identical calls and honors staleTime.+ * Falls back to a plain fetch when the cache isn't mounted yet.+ */+export async function cachedApiQuery<T>(+ query: { queryKey: unknown[]; staleTime: number },+ url: string+): Promise<T> {+ const queryFn = async (): Promise<T> => {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`Request failed with status ${res.status}`);+ return res.json();+ };+ const cache = getClientCache();+ if (!cache) return queryFn();+ return cache.fetchQuery({+ queryKey: query.queryKey,+ queryFn,+ staleTime: query.staleTime+ });+}++export function invalidateUserSelectQueries(companyId: string | null) {+ window.clientCache?.invalidateQueries({+ predicate: (query) => {+ const queryKey = query.queryKey as unknown[];+ return (+ USER_SELECT_QUERY_PREFIXES.includes(queryKey[0] as string) &&+ queryKey[1] === (companyId ?? "null")+ );+ }+ });+}diff --git a/conductor.json b/conductor.jsondeleted file mode 100644index b5c5acf42a..0000000000--- a/conductor.json+++ /dev/null@@ -1,7 +0,0 @@-{- "scripts": {- "setup": "echo \"$CONDUCTOR_WORKSPACE_NAME\" > .carbon-worktree && pnpm install && ./packages/dev/bin/crbn env sync && bash .ai/scripts/install-skills.sh",- "run": "./packages/dev/bin/crbn up --all",- "archive": "./packages/dev/bin/crbn down --volumes"- }-}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex ad5c1161cb..528a617910 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -59266,7 +59266,6 @@ export type Database = {amount: number | nullcompanyId: string | nullcreatedAt: string | null- createdBy: string | nullcustomFields: Json | nulldescription: string | nulldocumentId: string | null@@ -59334,41 +59333,6 @@ export type Database = {referencedRelation: "integrations"referencedColumns: ["companyId"]},- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },{foreignKeyName: "journalLine_intercompanyPartnerId_fkey"columns: ["intercompanyPartnerId"]@@ -65872,21 +65836,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71555,6 +71519,31 @@ export type Database = {thumbnailPath: string}[]}+ get_user_select_group_members: {+ Args: { p_company_id: string; p_group_id: string }+ Returns: Json+ }+ get_user_select_groups: {+ Args: {+ p_company_id: string+ p_limit?: number+ p_offset?: number+ p_search?: string+ p_type?: string+ }+ Returns: {+ groupCount: number+ id: string+ isCustomerOrgGroup: boolean+ isCustomerTypeGroup: boolean+ isEmployeeTypeGroup: boolean+ isRoot: boolean+ isSupplierOrgGroup: boolean+ isSupplierTypeGroup: boolean+ name: string+ userCount: number+ }[]+ }getConsolidationRates: {Args: {p_company_group_id: stringdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex ad5c1161cb..528a617910 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -59266,7 +59266,6 @@ export type Database = {amount: number | nullcompanyId: string | nullcreatedAt: string | null- createdBy: string | nullcustomFields: Json | nulldescription: string | nulldocumentId: string | null@@ -59334,41 +59333,6 @@ export type Database = {referencedRelation: "integrations"referencedColumns: ["companyId"]},- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "journalLine_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },{foreignKeyName: "journalLine_intercompanyPartnerId_fkey"columns: ["intercompanyPartnerId"]@@ -65872,21 +65836,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -71555,6 +71519,31 @@ export type Database = {thumbnailPath: string}[]}+ get_user_select_group_members: {+ Args: { p_company_id: string; p_group_id: string }+ Returns: Json+ }+ get_user_select_groups: {+ Args: {+ p_company_id: string+ p_limit?: number+ p_offset?: number+ p_search?: string+ p_type?: string+ }+ Returns: {+ groupCount: number+ id: string+ isCustomerOrgGroup: boolean+ isCustomerTypeGroup: boolean+ isEmployeeTypeGroup: boolean+ isRoot: boolean+ isSupplierOrgGroup: boolean+ isSupplierTypeGroup: boolean+ name: string+ userCount: number+ }[]+ }getConsolidationRates: {Args: {p_company_group_id: stringdiff --git a/packages/database/supabase/migrations/20260714045245_user-select-rpcs.sql b/packages/database/supabase/migrations/20260714045245_user-select-rpcs.sqlnew file mode 100644index 0000000000..0f9f89c817--- /dev/null+++ b/packages/database/supabase/migrations/20260714045245_user-select-rpcs.sql@@ -0,0 +1,141 @@+-- User-select rewrite: purpose-built, non-recursive, company-scoped group reads.+-- Replaces the recursive "groups" view on the user-select hot path.+-- SECURITY INVOKER: membership/user RLS applies to the caller.+-- plpgsql (not LANGUAGE sql) so the internal ORDER BY survives PostgREST.++CREATE OR REPLACE FUNCTION get_user_select_groups(+ p_company_id TEXT,+ p_type TEXT DEFAULT NULL,+ p_search TEXT DEFAULT NULL,+ p_limit INT DEFAULT 25,+ p_offset INT DEFAULT 0+) RETURNS TABLE (+ "id" TEXT,+ "name" TEXT,+ "isEmployeeTypeGroup" BOOLEAN,+ "isCustomerOrgGroup" BOOLEAN,+ "isCustomerTypeGroup" BOOLEAN,+ "isSupplierOrgGroup" BOOLEAN,+ "isSupplierTypeGroup" BOOLEAN,+ "userCount" INT,+ "groupCount" INT,+ "isRoot" BOOLEAN+) LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ -- Deterministic per-company root group ids. Must match the expressions in+ -- 20230123004632_groups.sql (create_employee_type_group / create_customer_type_group /+ -- create_supplier_type_group triggers).+ _roots TEXT[] := ARRAY[+ '00000000-0000-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12),+ '11111111-1111-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12),+ '22222222-2222-' || substring(p_company_id, 1, 4) || '-' || substring(p_company_id, 5, 4) || '-' || substring(p_company_id, 9, 12)+ ];+BEGIN+ RETURN QUERY+ SELECT+ g."id",+ g."name",+ g."isEmployeeTypeGroup",+ g."isCustomerOrgGroup",+ g."isCustomerTypeGroup",+ g."isSupplierOrgGroup",+ g."isSupplierTypeGroup",+ (SELECT count(*)::INT FROM "membership" m+ JOIN "user" u ON u."id" = m."memberUserId"+ WHERE m."groupId" = g."id" AND u."active" = TRUE) AS "userCount",+ (SELECT count(*)::INT FROM "membership" m+ WHERE m."groupId" = g."id" AND m."memberGroupId" IS NOT NULL) AS "groupCount",+ (g."id" = ANY(_roots)) AS "isRoot"+ FROM "group" g+ WHERE g."companyId" = p_company_id+ AND g."isIdentityGroup" = FALSE+ AND CASE+ WHEN p_type = 'employee' THEN NOT (+ g."isCustomerOrgGroup" OR g."isCustomerTypeGroup"+ OR g."isSupplierOrgGroup" OR g."isSupplierTypeGroup")+ WHEN p_type = 'customer' THEN (g."isCustomerTypeGroup" OR g."isCustomerOrgGroup")+ WHEN p_type = 'supplier' THEN (g."isSupplierTypeGroup" OR g."isSupplierOrgGroup")+ ELSE TRUE+ END+ AND CASE+ WHEN p_search IS NOT NULL AND p_search <> ''+ -- search mode: any depth, flat+ THEN g."name" ILIKE '%' || p_search || '%'+ -- browse mode: top-level only (roots, children of roots, parentless groups)+ ELSE (+ g."id" = ANY(_roots)+ OR EXISTS (SELECT 1 FROM "membership" m+ WHERE m."memberGroupId" = g."id" AND m."groupId" = ANY(_roots))+ OR NOT EXISTS (SELECT 1 FROM "membership" m WHERE m."memberGroupId" = g."id")+ )+ END+ ORDER BY+ (g."id" = ANY(_roots)) DESC,+ (g."isEmployeeTypeGroup" OR g."isCustomerTypeGroup" OR g."isSupplierTypeGroup") DESC,+ g."name" ASC,+ g."id" ASC+ LIMIT p_limit OFFSET p_offset;+END;+$$;++-- Direct members of one group: child groups (with counts) + direct active users.+CREATE OR REPLACE FUNCTION get_user_select_group_members(+ p_company_id TEXT,+ p_group_id TEXT+) RETURNS JSONB LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ _result JSONB;+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM "group" g+ WHERE g."id" = p_group_id AND g."companyId" = p_company_id+ ) THEN+ RETURN jsonb_build_object('groups', '[]'::jsonb, 'users', '[]'::jsonb);+ END IF;++ SELECT jsonb_build_object(+ 'groups', COALESCE((+ SELECT jsonb_agg(jsonb_build_object(+ 'id', cg."id",+ 'name', cg."name",+ 'isEmployeeTypeGroup', cg."isEmployeeTypeGroup",+ 'isCustomerOrgGroup', cg."isCustomerOrgGroup",+ 'isCustomerTypeGroup', cg."isCustomerTypeGroup",+ 'isSupplierOrgGroup', cg."isSupplierOrgGroup",+ 'isSupplierTypeGroup', cg."isSupplierTypeGroup",+ 'userCount', (SELECT count(*)::INT FROM "membership" m2+ JOIN "user" u2 ON u2."id" = m2."memberUserId"+ WHERE m2."groupId" = cg."id" AND u2."active" = TRUE),+ 'groupCount', (SELECT count(*)::INT FROM "membership" m3+ WHERE m3."groupId" = cg."id" AND m3."memberGroupId" IS NOT NULL)+ ) ORDER BY cg."name" ASC, cg."id" ASC)+ FROM "membership" m+ JOIN "group" cg ON cg."id" = m."memberGroupId"+ WHERE m."groupId" = p_group_id+ AND m."memberGroupId" IS NOT NULL+ AND cg."isIdentityGroup" = FALSE+ ), '[]'::jsonb),+ 'users', COALESCE((+ SELECT jsonb_agg(jsonb_build_object(+ 'id', u."id",+ 'firstName', u."firstName",+ 'lastName', u."lastName",+ 'fullName', u."fullName",+ 'email', u."email",+ 'avatarUrl', u."avatarUrl"+ ) ORDER BY u."lastName" ASC, u."firstName" ASC, u."id" ASC)+ FROM "membership" m+ JOIN "user" u ON u."id" = m."memberUserId"+ WHERE m."groupId" = p_group_id+ AND m."memberUserId" IS NOT NULL+ AND u."active" = TRUE+ ), '[]'::jsonb)+ ) INTO _result;++ RETURN _result;+END;+$$;++NOTIFY pgrst, 'reload schema';diff --git a/packages/dev/AGENTS.md b/packages/dev/AGENTS.mdindex b38dc7fd0e..ebf8fda4be 100644--- a/packages/dev/AGENTS.md+++ b/packages/dev/AGENTS.md@@ -30,9 +30,10 @@ pnpm --filter @carbon/dev typecheck # tsgo --noEmit## Key Patterns-- **Commands**: `up`, `down`, `new`, `remove`, `list`, `status`, `reset`, `migrate`, `copy` (env sync)+- **Commands**: `up`, `down` (`--purge` releases the slot), `new`, `init`, `remove`, `list`, `status`, `reset`, `migrate`, `copy` (env sync)- **Stack boot** (`commands/up.ts`): Docker Compose → wait Postgres → migrations → regen types → spawn apps → portless aliases-- **Worktree** (`worktree.ts`): `resolveSlug()`, `getWorktreeRoot()`, `projectName()`, `ensureSlugAvailable()`+- **Provision** (`commands/init.ts`): `crbn init` provisions an already-created worktree (canonical slug + env sync + skills) to match a `crbn checkout`; shared by `new`, the bash `checkout` post-create hook, and Conductor's `setup` (`.conductor/settings.toml`). It does NOT boot the stack — `crbn up` still mints ports/`.env.local`.+- **Worktree** (`worktree.ts`): `resolveSlug()`, `canonicalSlug()` (branch-derived `<repoBase>-<branch>`), `getWorktreeRoot()`, `projectName()`, `ensureSlugAvailable()`- **Services**: `compose.ts` (Docker), `migrations.ts` (Postgres/Supabase), `portless.ts` (`.dev` URLs), `apps.ts` (dev servers)- **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/bin/crbn b/packages/dev/bin/crbnindex a8e9576e9c..a45bcc672b 100755--- a/packages/dev/bin/crbn+++ b/packages/dev/bin/crbn@@ -398,21 +398,15 @@ _checkout_pr_no_gh() {maybe_up "$target" "$do_up"}-# crbn env sync inside the new worktree (so it reads package.json#crbn.copy-# from the main checkout via --git-common-dir). All output goes to stderr to-# keep stdout reserved for the eval'd `cd` line.+# Provision the freshly-created worktree via `crbn init`: sets the canonical+# slug, syncs `.env`/copy-files from main, and links .ai skills into+# .claude/.codex (all gitignored, so a fresh worktree has none). Run inside the+# worktree so it reads package.json#crbn.copy from main via --git-common-dir.+# All output goes to stderr to keep stdout reserved for the eval'd `cd` line.do_post_create() {local target="$1"- if ! ( cd "$target" && delegate_ts env sync >&2 ); then- warn "env sync step failed (worktree was still created)"- fi- # Link .ai skills/rules into .claude/.codex for this worktree. They're- # gitignored, so a fresh worktree has none until this runs. Output to stderr- # so the checkout stdout (the eval'd `cd`) stays clean.- if [[ -f "$target/.ai/scripts/install-skills.sh" ]]; then- if ! ( cd "$target" && bash .ai/scripts/install-skills.sh >&2 ); then- warn "install-skills step failed (worktree was still created)"- fi+ if ! ( cd "$target" && delegate_ts init >&2 ); then+ warn "init step failed (worktree was still created)"fi}@@ -440,6 +434,7 @@ crbn — Carbon dev CLIcrbn checkout -b <branch> New branch + worktree (--base REF).crbn checkout <pr-number> PR → worktree; git push updates the PR (needs gh).crbn new [branch] Interactive worktree creation.+ crbn init Provision the current worktree (slug/env/skills).crbn list Show all worktrees with stack status.crbn remove [--prune] Multi-select worktrees to delete.--prune also deletes the git branch.@@ -451,6 +446,7 @@ crbn — Carbon dev CLIcrbn up --borrow Reuse another worktree's containers.crbn up --no-apps Services only, no dev servers.crbn down Stop stack (volumes preserved).+ crbn down --purge Stop stack, wipe volumes, release the slot.crbn reset Wipe volumes + redis, then up.crbn status Port assignment + container health.crbn migrate Apply DB migrations (loads .env.local).@@ -484,7 +480,7 @@ case "$cmd" incheckout)cmd_checkout "$@";;- copy|env|up|down|reset|status|migrate|new|list|remove|complete)+ copy|env|up|down|reset|status|migrate|new|init|list|remove|complete)delegate_ts "$cmd" "$@";;*)diff --git a/packages/dev/src/commands/down.ts b/packages/dev/src/commands/down.tsindex f45bca0b24..9e5d076574 100644--- a/packages/dev/src/commands/down.ts+++ b/packages/dev/src/commands/down.ts@@ -3,12 +3,13 @@ import pc from "picocolors";import { syncAppPortlessConfigs } from "../env.js";import { currentBranch } from "../git.js";import { killOrphanedApps, killOrphanedStripe } from "../services/apps.js";-import { stopStack } from "../services/compose.js";+import { flushDb, stopStack } from "../services/compose.js";import { branchToPrefix, unregisterAliases } from "../services/portless.js";import {getSlot,getWorktreeRoot,projectName,+ removeSlot,resolveSlug} from "../worktree.js";@@ -16,18 +17,22 @@ import {// the freshly-interrupted stdin; fall back to plain printf progress.// volumes: also drop the stack's Docker volumes (data is wiped) — for headless// dispatch teardown where leftover volumes would accumulate on a long-lived box.-export async function down(opts: { silent?: boolean; volumes?: boolean } = {}) {+export async function down(+ opts: { silent?: boolean; volumes?: boolean; purge?: boolean } = {}+) {const root = await getWorktreeRoot();const slug = resolveSlug(root);const project = projectName(slug);- const withVolumes = opts.volumes ?? false;+ const purge = opts.purge ?? false;+ // Purge is a full teardown (workspace archive/removal) — it implies volumes.+ const withVolumes = (opts.volumes ?? false) || purge;// No ensureSlugAvailable guard here — `down` is the user explicitly asking// to stop their own stack. The guard (meant for `up`) would block teardown// of moved/borrowed/stale worktrees, leaving containers orphaned.if (opts.silent) {- return runPlain(root, slug, project, withVolumes);+ return runPlain(root, slug, project, withVolumes, purge);}intro("Carbon · dev down");@@ -68,16 +73,34 @@ export async function down(opts: { silent?: boolean; volumes?: boolean } = {}) {syncAppPortlessConfigs(root);return "configs reset";}- }+ },+ // Purge: release the worktree's registry slot (ports/jwt) and flush its+ // redis db, so archived/removed workspaces don't leak slots from the pool.+ ...(purge+ ? [+ {+ title: "Release port slot + flush redis",+ task: async () => {+ const slot = getSlot(slug);+ if (slot && typeof slot.redisDb === "number") {+ await flushDb(slot.redisDb);+ }+ removeSlot(slug);+ return "slot released";+ }+ }+ ]+ : [])]);- outro("stopped");+ outro(purge ? "stopped and purged" : "stopped");}async function runPlain(root: string,slug: string,project: string,- withVolumes: boolean+ withVolumes: boolean,+ purge: boolean) {const step = (msg: string) =>process.stderr.write(`${pc.cyan("•")} ${msg}…\n`);@@ -110,4 +133,12 @@ async function runPlain(step("cleaning up portless.json");syncAppPortlessConfigs(root);done("configs reset");++ if (purge) {+ step("releasing port slot + flushing redis");+ const slot = getSlot(slug);+ if (slot && typeof slot.redisDb === "number") await flushDb(slot.redisDb);+ removeSlot(slug);+ done("slot released");+ }}diff --git a/packages/dev/src/commands/init.test.ts b/packages/dev/src/commands/init.test.tsnew file mode 100644index 0000000000..a8e5d2024c--- /dev/null+++ b/packages/dev/src/commands/init.test.ts@@ -0,0 +1,80 @@+import { execFileSync } from "node:child_process";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "pathe";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { canonicalSlug } from "../worktree.js";+import { initWorktree } from "./init.js";++// Real git worktrees: prove `crbn init` provisions the worktree it's POINTED at+// (`opts.root`), not the caller/main checkout, and that the main-checkout guard+// (isLinkedWorktree = normalized git-dir vs git-common-dir) holds.+const git = (cwd: string, ...args: string[]) =>+ execFileSync("git", args, {+ cwd,+ stdio: "pipe",+ env: {+ ...process.env,+ GIT_AUTHOR_NAME: "t",+ GIT_AUTHOR_EMAIL: "t@t",+ GIT_COMMITTER_NAME: "t",+ GIT_COMMITTER_EMAIL: "t@t"+ }+ });++describe("initWorktree", () => {+ const parent = mkdtempSync(join(tmpdir(), "carbon-init-"));+ // basename "carbon" (no `-slug` suffix) → repoBase resolves to "carbon".+ const mainDir = join(parent, "carbon");+ const wtDir = join(parent, "wt-codename");+ const branch = "feat-scope-test";+ const slugFile = ".carbon-worktree";++ beforeAll(() => {+ mkdirSync(mainDir, { recursive: true });+ git(mainDir, "init", "-q");+ writeFileSync(join(mainDir, "README.md"), "x\n");+ writeFileSync(join(mainDir, ".env"), "SECRET=1\n");+ writeFileSync(+ join(mainDir, "package.json"),+ JSON.stringify({ name: "carbon", crbn: { copy: [".env"] } })+ );+ git(mainDir, "add", "-A");+ git(mainDir, "commit", "-qm", "init");+ // Conductor-style: a linked worktree whose dir name is NOT the branch.+ git(mainDir, "worktree", "add", "-q", "-b", branch, wtDir);+ });++ afterAll(() => rmSync(parent, { recursive: true, force: true }));++ it("writes the branch-derived slug under the target root, not main", async () => {+ await initWorktree({ root: wtDir, quiet: true });++ const expected = canonicalSlug({+ worktreeRoot: wtDir,+ mainRoot: mainDir,+ branch+ });+ expect(expected).toBe("carbon-feat-scope-test");+ expect(readFileSync(join(wtDir, slugFile), "utf8").trim()).toBe(expected);+ // Must NOT have provisioned the main checkout.+ expect(existsSync(join(mainDir, slugFile))).toBe(false);+ });++ it("syncs copy-files (.env) into the target worktree", async () => {+ await initWorktree({ root: wtDir, quiet: true });+ expect(readFileSync(join(wtDir, ".env"), "utf8")).toContain("SECRET=1");+ });++ it("refuses to initialize the main checkout (guard)", async () => {+ await initWorktree({ root: mainDir, quiet: true });+ expect(existsSync(join(mainDir, slugFile))).toBe(false);+ });+});diff --git a/packages/dev/src/commands/init.ts b/packages/dev/src/commands/init.tsnew file mode 100644index 0000000000..fb4de7e440--- /dev/null+++ b/packages/dev/src/commands/init.ts@@ -0,0 +1,88 @@+import { existsSync } from "node:fs";+import { intro, log, outro } from "@clack/prompts";+import { execa } from "execa";+import { join } from "pathe";+import pc from "picocolors";+import { currentBranch, isLinkedWorktree, mainCheckoutRoot } from "../git.js";+import {+ canonicalSlug,+ ensureSlugAvailable,+ getWorktreeRoot,+ persistSlug,+ projectName+} from "../worktree.js";+import { syncStaleCopyFiles } from "./copy.js";++// `crbn init` — provision the CURRENT worktree so it matches a `crbn checkout`+// worktree: a deterministic, branch-derived slug (`.carbon-worktree`), the+// copy-files (`.env`) synced from the main checkout, and the AI skills linked.+// Idempotent. Leaves the heavy stack boot — ports, `.env.local`, containers —+// to `crbn up`. Shared by `crbn new`, the `checkout` post-create hook, and+// Conductor's `setup` script (which creates the worktree itself, then calls us).+export async function initWorktree(opts?: {+ /** Worktree to provision. Defaults to the current one. */+ root?: string;+ /** Sync `.env` (and other package.json#crbn.copy files) from main. */+ copyEnv?: boolean;+ /** Suppress clack output — for use inside another command's task spinner. */+ quiet?: boolean;+}) {+ const root = opts?.root ?? (await getWorktreeRoot());+ const copyEnv = opts?.copyEnv !== false;+ const quiet = opts?.quiet === true;+ const say = (fn: () => void) => {+ if (!quiet) fn();+ };++ say(() => intro("Carbon · init worktree"));++ // Never re-slug the main checkout — that would clobber its `.carbon-worktree`+ // and collapse every linked worktree onto the main stack.+ if (!(await isLinkedWorktree(root))) {+ say(() =>+ log.warn("main checkout — nothing to initialize (init is for worktrees)")+ );+ say(() => outro(""));+ return;+ }++ const mainRoot = await mainCheckoutRoot(root);+ const branch = await currentBranch(root);+ const slug = canonicalSlug({ worktreeRoot: root, mainRoot, branch });++ // Refuse to steal a slug that a *different* live stack already owns. No-op+ // (returns silently) when Docker isn't running yet — common during setup.+ await ensureSlugAvailable(slug, root);+ persistSlug(root, slug);+ say(() =>+ log.info(`worktree: ${pc.cyan(slug)} (project ${projectName(slug)})`)+ );++ if (copyEnv) {+ const copied = await syncStaleCopyFiles(root);+ say(() =>+ log.info(+ copied.length+ ? `synced from main: ${copied.join(", ")}`+ : "copy-files already current"+ )+ );+ }++ await installSkills(root, say);++ say(() => outro(`ready — ${pc.cyan("crbn up")} to boot the stack`));+}++// Link `.ai` rules/skills into `.claude`/`.codex` (both gitignored, so absent in+// a fresh worktree). Idempotent — the script re-points existing symlinks.+async function installSkills(root: string, say: (fn: () => void) => void) {+ const script = join(root, ".ai", "scripts", "install-skills.sh");+ if (!existsSync(script)) return;+ const r = await execa("bash", [script], { cwd: root, reject: false });+ say(() =>+ r.exitCode === 0+ ? log.info("skills linked into .claude/.codex")+ : log.warn("install-skills step failed (worktree still initialized)")+ );+}diff --git a/packages/dev/src/commands/new.ts b/packages/dev/src/commands/new.tsindex dd176027ca..3b7ed0247b 100644--- a/packages/dev/src/commands/new.ts+++ b/packages/dev/src/commands/new.ts@@ -1,6 +1,6 @@-import { copyFileSync, existsSync, writeFileSync } from "node:fs";+import { writeFileSync } from "node:fs";import { intro, outro, tasks } from "@clack/prompts";-import { basename, dirname, join, relative, resolve } from "pathe";+import { basename, dirname, relative, resolve } from "pathe";import pc from "picocolors";import { addWorktree, currentBranch } from "../git.js";import {@@ -10,6 +10,7 @@ import {promptDirName} from "../prompts.js";import { getWorktreeRoot, slugify } from "../worktree.js";+import { initWorktree } from "./init.js";export async function newWorktree(opts?: {branch?: string;@@ -59,19 +60,16 @@ export async function newWorktree(opts?: {return `worktree at ${relative(here, targetPath)}`;}},- ...(copyEnv- ? [- {- title: "Copy .env",- task: async () => {- const src = join(here, ".env");- if (!existsSync(src)) return "no .env in source — skipped";- copyFileSync(src, join(targetPath, ".env"));- return ".env copied";- }- }- ]- : [])+ {+ title: "Provision worktree",+ task: async (msg) => {+ msg("slug + env sync + skills");+ await initWorktree({ root: targetPath, copyEnv, quiet: true });+ return copyEnv+ ? "slug set, .env synced, skills linked"+ : "slug set, skills linked";+ }+ }]);// Write target path so the shell wrapper can cd into the new worktree.diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.tsindex 9187c427a7..42eb6e8ced 100644--- a/packages/dev/src/main.ts+++ b/packages/dev/src/main.ts@@ -1,6 +1,7 @@import { defineCommand, runMain } from "citty";import { copy, envSync } from "./commands/copy.js";import { down } from "./commands/down.js";+import { initWorktree } from "./commands/init.js";import { listWorktrees } from "./commands/list.js";import { migrate } from "./commands/migrate.js";import { newWorktree } from "./commands/new.js";@@ -98,9 +99,16 @@ const main = defineCommand({type: "boolean",default: false,description: "Also remove Docker volumes (the stack's data is wiped)"+ },+ purge: {+ type: "boolean",+ default: false,+ description:+ "Full teardown for archive/removal: remove volumes, flush redis, and release the port slot"}},- run: ({ args }) => down({ volumes: args.volumes === true })+ run: ({ args }) =>+ down({ volumes: args.volumes === true, purge: args.purge === true })}),reset: defineCommand({meta: { description: "Wipe volumes + flush redis db, then `up`" },@@ -174,6 +182,21 @@ const main = defineCommand({yes: args.yes === true})}),+ init: defineCommand({+ meta: {+ description:+ "Provision the current worktree (slug + env sync + skills) to match a `crbn checkout`"+ },+ args: {+ "copy-env": {+ type: "boolean",+ default: true,+ description:+ "Sync .env from the main checkout (--no-copy-env to skip)"+ }+ },+ run: ({ args }) => initWorktree({ copyEnv: args["copy-env"] !== false })+ }),list: defineCommand({meta: { description: "List worktrees with stack status" },run: () => listWorktrees()diff --git a/packages/dev/src/worktree.test.ts b/packages/dev/src/worktree.test.tsindex 3d627470c5..3b0c20c70f 100644--- a/packages/dev/src/worktree.test.ts+++ b/packages/dev/src/worktree.test.ts@@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, symlinkSync, unlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "pathe";import { afterAll, describe, expect, it } from "vitest";-import { sameWorktreePath, slugify } from "./worktree.js";+import { canonicalSlug, sameWorktreePath, slugify } from "./worktree.js";describe("slugify", () => {it("lowercases", () => {@@ -37,6 +37,58 @@ describe("slugify", () => {});});+describe("canonicalSlug", () => {+ it("derives <repoBase>-<branch> independent of the worktree path", () => {+ // Conductor codename dir (`moscow`) must NOT drive the slug — the branch does.+ expect(+ canonicalSlug({+ worktreeRoot: "/Users/x/conductor/workspaces/carbon/moscow",+ mainRoot: "/Users/x/Code/carbon",+ branch: "featuser-select"+ })+ ).toBe("carbon-featuser-select");+ });++ it("sanitizes slashes in the branch (matches `crbn new` dir naming)", () => {+ expect(+ canonicalSlug({+ worktreeRoot: "/Users/x/anything",+ mainRoot: "/Users/x/Code/carbon",+ branch: "feat/service"+ })+ ).toBe("carbon-feat-service");+ });++ it("strips a prior -<slug> suffix from the main checkout basename", () => {+ expect(+ canonicalSlug({+ worktreeRoot: "/Users/x/wt",+ mainRoot: "/Users/x/Code/carbon-standard-costing",+ branch: "fix-bug"+ })+ ).toBe("carbon-fix-bug");+ });++ it("never collides with the main checkout's bare `carbon` slug", () => {+ const slug = canonicalSlug({+ worktreeRoot: "/Users/x/conductor/workspaces/carbon/macau",+ mainRoot: "/Users/x/Code/carbon",+ branch: "some-feature"+ });+ expect(slug).not.toBe("carbon");+ });++ it("falls back to the worktree dir basename when HEAD is detached", () => {+ expect(+ canonicalSlug({+ worktreeRoot: "/Users/x/conductor/workspaces/carbon/moscow",+ mainRoot: "/Users/x/Code/carbon",+ branch: ""+ })+ ).toBe("moscow");+ });+});+describe("sameWorktreePath", () => {const real = mkdtempSync(join(tmpdir(), "carbon-worktree-"));const link = `${real}-link`;diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.tsindex 0083b28c58..361ad9bc7c 100644--- a/packages/dev/src/worktree.ts+++ b/packages/dev/src/worktree.ts@@ -63,6 +63,23 @@ export function persistSlug(worktreeRoot: string, slug: string) {writeFileSync(join(worktreeRoot, SLUG_FILE), `${slug}\n`);}+// Canonical, branch-derived slug: "<repoBase>-<branch>" — the same directory+// name `crbn new` derives (new.ts). Path-independent, so a worktree created by+// Conductor (a codename dir like `moscow`) or a bare `git worktree add` gets the+// SAME slug a native `crbn` worktree would, instead of `basename` colliding with+// the main checkout's `carbon`. Falls back to the worktree dir basename when the+// branch is missing / HEAD-detached.+export function canonicalSlug(opts: {+ worktreeRoot: string;+ mainRoot: string;+ branch: string;+}): string {+ const repoBase = basename(opts.mainRoot).replace(/-[a-z0-9-]+$/i, "");+ return opts.branch+ ? slugify(`${repoBase}-${opts.branch}`)+ : slugify(basename(opts.worktreeRoot));+}+export async function getWorktreeRoot(): Promise<string> {try {const r = await execa("git", ["rev-parse", "--show-toplevel"]);