Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix: calculator null guard & drop workspace role converge statements (#17588)

Rdmclin227aa50bb951c
diff --git a/packages/builtin-tool-calculator/src/calculate.test.ts b/packages/builtin-tool-calculator/src/calculate.test.ts
index 09315393c01..cfdc0ad9700 100644
--- a/packages/builtin-tool-calculator/src/calculate.test.ts
+++ b/packages/builtin-tool-calculator/src/calculate.test.ts
@@ -1,4 +1,5 @@
-import { describe, expect, it } from 'vitest';
+import nerdamer from 'nerdamer-prime/all';
+import { describe, expect, it, vi } from 'vitest';
import { calculatorExecutor } from '../src/executor';
@@ -1323,6 +1324,28 @@ describe('Calculator Equation Solver', () => {
expect(parsed.y).toBe('1');
});
+ it('should report an unsolvable system instead of dereferencing an empty result', async () => {
+ // Newer nerdamer returns nothing for an unsolvable system rather than
+ // throwing. Assert the guard's own message: the surrounding catch turns
+ // *any* failure β€” including a dereference TypeError β€” into the same
+ // `success: false` / `SolveError` pair, so those two alone cannot tell
+ // the guarded path from the unguarded one.
+ const spy = vi.spyOn(nerdamer, 'solveEquations').mockReturnValue(null as never);
+
+ try {
+ const result = await calculatorExecutor.solve({
+ equation: ['x+y=1', 'x+y=2'],
+ variable: ['x', 'y'],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error?.type).toBe('SolveError');
+ expect(result.content).toBe('No solution found for the given system of equations');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
it('should solve system of two equations with default variables', async () => {
const result = await calculatorExecutor.solve({
equation: ['3*x+2*y=7', 'x-y=1'],
@@ -1355,7 +1378,9 @@ describe('Calculator Equation Solver', () => {
expect(result.success).toBe(false);
expect(result.error?.type).toBe('SolveError');
- expect(result.content).toContain('distinct solution');
+ // Older nerdamer throws ("does not have a distinct solution"); newer
+ // versions return nothing and the no-solution guard answers instead.
+ expect(result.content).toMatch(/distinct solution|No solution found/);
});
it('should handle single equation with extra variables in array', async () => {
diff --git a/packages/builtin-tool-calculator/src/executor/index.ts b/packages/builtin-tool-calculator/src/executor/index.ts
index aa6a4962ac8..df2defbbad3 100644
--- a/packages/builtin-tool-calculator/src/executor/index.ts
+++ b/packages/builtin-tool-calculator/src/executor/index.ts
@@ -373,6 +373,21 @@ class CalculatorExecutor
}
const result = nerdamer.solveEquations(equation, solveVariables);
+
+ // `solveEquations` yields nothing for an unsolvable system. The
+ // single-equation branch above already surfaces that as a SolveError;
+ // mirror it here instead of dereferencing the empty result.
+ if (!result) {
+ return {
+ content: 'No solution found for the given system of equations',
+ error: {
+ message: 'No solution found',
+ type: 'SolveError',
+ },
+ success: false,
+ };
+ }
+
const rawResult = result.toString();
const pairs = rawResult.split(',');
diff --git a/packages/database/src/index.ts b/packages/database/src/index.ts
index ff9652e47b4..5bc3a3750d4 100644
--- a/packages/database/src/index.ts
+++ b/packages/database/src/index.ts
@@ -4,4 +4,3 @@ export * from './repositories/onboardingUnderstanding';
export * from './type';
export * from './utils/idGenerator';
export * from './utils/workspace';
-export * from './utils/workspaceAdminRollout';
diff --git a/packages/database/src/utils/__tests__/workspaceAdminRollout.test.ts b/packages/database/src/utils/__tests__/workspaceAdminRollout.test.ts
deleted file mode 100644
index 4bd9db31d53..00000000000
--- a/packages/database/src/utils/__tests__/workspaceAdminRollout.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-// @vitest-environment node
-import { eq, sql } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-
-import { getTestDB } from '../../core/getTestDB';
-import {
- roles,
- userRoles,
- users,
- workspaceInvitations,
- workspaceMembers,
- workspaces,
-} from '../../schemas';
-import type { LobeChatDatabase } from '../../type';
-import { WORKSPACE_ROLE_CONVERGE_STATEMENTS } from '../workspaceAdminRollout';
-
-const serverDB: LobeChatDatabase = await getTestDB();
-const ownerId = 'role-converge-owner';
-const legacyOwnerId = 'role-converge-legacy-owner';
-const driftedMemberId = 'role-converge-drifted-member';
-const workspaceId = 'role-converge-workspace';
-const invitationId = 'role-converge-invitation';
-
-const runConverge = async () => {
- for (const statement of WORKSPACE_ROLE_CONVERGE_STATEMENTS) {
- await serverDB.execute(sql.raw(statement.sql));
- }
-};
-
-const cleanup = async () => {
- await serverDB.delete(userRoles);
- await serverDB.delete(roles);
- await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));
- await serverDB.delete(users);
-};
-
-beforeEach(async () => {
- await cleanup();
- await serverDB
- .insert(users)
- .values([{ id: ownerId }, { id: legacyOwnerId }, { id: driftedMemberId }]);
- await serverDB.insert(workspaces).values({
- id: workspaceId,
- name: 'Role converge',
- primaryOwnerId: ownerId,
- slug: workspaceId,
- });
- await serverDB.insert(workspaceMembers).values([
- // Primary owner's row is soft-deleted and mislabelled β€” must be repaired.
- { deletedAt: new Date(), role: 'member', userId: ownerId, workspaceId },
- // Legacy co-owner without any RBAC grant falls back to admin.
- { role: 'owner', userId: legacyOwnerId, workspaceId },
- // Drifted row: column says owner, but the legacy RBAC grant (the
- // pre-reversal truth) says member β€” must reconcile to member.
- { role: 'owner', userId: driftedMemberId, workspaceId },
- ]);
- const [memberRole] = await serverDB
- .insert(roles)
- .values({
- displayName: 'Member',
- isActive: true,
- isSystem: true,
- name: 'workspace_member',
- workspaceId,
- })
- .returning({ id: roles.id });
- await serverDB
- .insert(userRoles)
- .values({ roleId: memberRole.id, userId: driftedMemberId, workspaceId });
- // An expired member grant on the stray co-owner must be ignored β€” the
- // convergence mirrors the RBAC checks' active/non-expired predicates, so
- // this row falls through to the admin fallback instead of becoming member.
- await serverDB.insert(userRoles).values({
- expiresAt: new Date(Date.now() - 86_400_000),
- roleId: memberRole.id,
- userId: legacyOwnerId,
- workspaceId,
- });
- await serverDB.insert(workspaceInvitations).values({
- email: '[email protected]',
- expiresAt: new Date(Date.now() + 86_400_000),
- id: invitationId,
- inviterId: ownerId,
- role: 'owner',
- token: `${invitationId}-token`,
- workspaceId,
- });
-});
-
-afterEach(cleanup);
-
-describe('workspace role convergence statements', () => {
- it('converges legacy rows to the four-role model and is idempotent', async () => {
- await runConverge();
- await runConverge();
-
- const memberships = await serverDB.query.workspaceMembers.findMany({
- where: eq(workspaceMembers.workspaceId, workspaceId),
- });
-
- const primary = memberships.find(({ userId }) => userId === ownerId);
- expect(primary?.role).toBe('owner');
- expect(primary?.deletedAt).toBeNull();
-
- expect(memberships.find(({ userId }) => userId === legacyOwnerId)?.role).toBe('admin');
- expect(memberships.find(({ userId }) => userId === driftedMemberId)?.role).toBe('member');
-
- const invitation = await serverDB.query.workspaceInvitations.findFirst({
- where: eq(workspaceInvitations.id, invitationId),
- });
- expect(invitation?.role).toBe('admin');
- });
-});
diff --git a/packages/database/src/utils/workspaceAdminRollout.ts b/packages/database/src/utils/workspaceAdminRollout.ts
deleted file mode 100644
index eed86a6d355..00000000000
--- a/packages/database/src/utils/workspaceAdminRollout.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * Four-role rollout data convergence (LOBE-12329).
- *
- * `workspace_members.role` is the single source of truth for built-in
- * workspace roles; permissions expand from the in-code
- * `WORKSPACE_ROLE_PERMISSIONS` matrix at request time. The only data work the
- * rollout needs is converging legacy rows to the four-role model:
- *
- * 1. the primary owner's membership row is repaired if missing /
- * soft-deleted / mislabelled;
- * 2. drifted non-primary rows are reconciled from the legacy RBAC grants β€”
- * the pre-reversal source of truth β€” while those rows still exist
- * (a non-primary owner grant converges to admin);
- * 3. leftover stray `owner` labels without any grant fall back to `admin`;
- * 4. pending Owner invitations become Admin (Owner is only produced via
- * ownership transfer).
- *
- * Run via `scripts/workspace-rbac-backfill` in the cloud repo. Every
- * statement is idempotent; once they converge, the
- * `workspace_members_unique_active_owner_idx` index-only migration can ship.
- */
-
-export interface WorkspaceRoleConvergeStatement {
- label: string;
- sql: string;
-}
-
-export const WORKSPACE_ROLE_CONVERGE_STATEMENTS: WorkspaceRoleConvergeStatement[] = [
- {
- label: 'repair-primary-owner-membership',
- sql: `
-INSERT INTO "workspace_members" (
- "workspace_id",
- "user_id",
- "role",
- "joined_at",
- "updated_at",
- "deleted_at"
-)
-SELECT
- "workspaces"."id",
- "workspaces"."primary_owner_id",
- 'owner',
- now(),
- now(),
- NULL
-FROM "workspaces"
-ON CONFLICT ("workspace_id", "user_id") DO UPDATE SET
- "role" = 'owner',
- "deleted_at" = NULL,
- "updated_at" = now();`,
- },
- {
- // Column/RBAC drift existed before the reversal (the column could lag a
- // role change while RBAC rows were authoritative). While the legacy
- // workspace-scoped grants are still in the DB, use them as the
- // last-known truth: write each non-primary member's RBAC projection back
- // into the column. A non-primary owner grant converges to admin (the
- // unique Owner is the primary owner). No-ops once the grants are
- // physically cleaned up.
- label: 'reconcile-non-primary-roles-from-rbac-grants',
- sql: `
-UPDATE "workspace_members"
-SET "role" = "projection"."resolved", "updated_at" = now()
-FROM (
- SELECT
- "rbac_user_roles"."user_id",
- "rbac_user_roles"."workspace_id",
- CASE min(array_position(
- ARRAY['workspace_owner', 'workspace_admin', 'workspace_member', 'workspace_viewer'],
- "rbac_roles"."name"
- ))
- WHEN 1 THEN 'admin'
- WHEN 2 THEN 'admin'
- WHEN 3 THEN 'member'
- WHEN 4 THEN 'viewer'
- END AS "resolved"
- FROM "rbac_user_roles"
- INNER JOIN "rbac_roles"
- ON "rbac_roles"."id" = "rbac_user_roles"."role_id"
- AND "rbac_roles"."workspace_id" = "rbac_user_roles"."workspace_id"
- WHERE "rbac_roles"."name" IN (
- 'workspace_owner', 'workspace_admin', 'workspace_member', 'workspace_viewer'
- )
- -- Mirror the predicates of the RBAC checks this data replaces: inactive
- -- roles and expired grants were never authoritative.
- AND "rbac_roles"."is_active" = true
- AND ("rbac_user_roles"."expires_at" IS NULL OR "rbac_user_roles"."expires_at" > now())
- GROUP BY "rbac_user_roles"."user_id", "rbac_user_roles"."workspace_id"
-) AS "projection", "workspaces"
-WHERE
- "workspace_members"."workspace_id" = "projection"."workspace_id"
- AND "workspace_members"."user_id" = "projection"."user_id"
- AND "workspaces"."id" = "workspace_members"."workspace_id"
- AND "workspace_members"."user_id" <> "workspaces"."primary_owner_id"
- AND "workspace_members"."deleted_at" IS NULL
- AND "projection"."resolved" IS NOT NULL
- AND "workspace_members"."role" IS DISTINCT FROM "projection"."resolved";`,
- },
- {
- // Leftover stray owners without any RBAC grant (nothing to reconcile
- // against) fall back to admin β€” the historical UI meaning of a
- // non-primary owner label.
- label: 'relabel-non-primary-owners-admin',
- sql: `
-UPDATE "workspace_members"
-SET "role" = 'admin', "updated_at" = now()
-FROM "workspaces"
-WHERE
- "workspace_members"."workspace_id" = "workspaces"."id"
- AND "workspace_members"."user_id" <> "workspaces"."primary_owner_id"
- AND "workspace_members"."role" = 'owner';`,
- },
- {
- label: 'convert-owner-invitations-admin',
- sql: `
-UPDATE "workspace_invitations"
-SET "role" = 'admin', "updated_at" = now()
-WHERE "role" = 'owner';`,
- },
-];