refactor(model-pool): scope disabled-models by company; cascade on delete (v42)

The per-connector "enabled/disabled model" settings lived under a
global key in the settings key-value table
(`disabled_models:${connectorId}`). No company dimension. Deleting a
company left the pool choices behind, and creating a new company
silently inherited them — the visible symptom was "onboarding's team-
model configuration survives company deletion and pollutes the next
company's CEO model list."

Root fix, not a cleanup hook: the storage becomes a real relational
table with `(company_id, connector_id)` primary key and an
`ON DELETE CASCADE` FK from `companies`. Company deletion wipes pool
config by construction; no cleanup step in `deleteCompany()` can
drift.

Schema (migration v42):
- CREATE TABLE connector_model_pool_settings (company_id, connector_id,
  disabled_models_json, updated_at), PK (company_id, connector_id),
  FK companies(id) ON DELETE CASCADE.
- Drop every `settings.disabled_models:*` key — these were the bug's
  residue; there is no right company to attribute them to, so the
  migration clears them. Users re-select on next onboarding.

API surgery — every reader/writer now takes companyId:
- db.getDisabledModels(companyId, connectorId)
- db.setDisabledModels(companyId, connectorId, models)
- db.hasModelPoolSettings(companyId, connectorId)
- connector-model-policy: getConnectorModelPolicy(deps, companyId,
  connectorId); validateConnectorModelSelection(deps, companyId,
  connectorId, model)
- model-dispatch: listEnabledModels(companyId, deps);
  pickModelForAgent resolves companyId from agent.companyId
- orchestration heartbeat/task-runner/turn-context/run-dispatch pass
  the agent's or run's companyId through to the policy deps
- IPC schema: connectorDisabledModelsSchema gains companyId; new
  connectorModelPoolQuerySchema pairs companyId+connectorId for reads

Onboarding becomes commit-on-launch:
- useConnectorModelSelection no longer persists via IPC during
  onboarding. Toggles mutate local state; it exposes `poolSelections`
  to the wizard.
- bootstrapOnboardingSchema gains connectorPoolSelections. The
  onboarding service saves the company first, then persists each
  per-connector disabled list scoped to the new company id — CEO
  model validation runs against the company's freshly-persisted pool,
  not some stale global.
- IPC setConnectorDisabledModels now requires companyId; the only
  consumer was onboarding, which no longer calls it at all.
- Main-side listConnectorModels returns the raw provider catalog
  (no pool filtering), since that IPC is used from onboarding where
  no company exists yet; pool filtering happens at dispatch time.

saveConnector IPC drops the per-company pool validation — connector
config is a global hint, company-scoped enforcement belongs at run
dispatch where the company is known.

Tests: 603/603 green. Typecheck clean. Integration tests rewritten
to set the pool via connectorPoolSelections on bootstrap input, not
a pre-bootstrap global setDisabledModels call.
This commit is contained in:
ZacharyZhang-NY committed 2026-04-18 22:14:09 -04:00
1 parent 2ace9183b0
commit d75bfd5851
22 files changed
+270 -135

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
import log from "electron-log/main.js";
import type { Migration, MigrationDeps } from "./types";
import { tableExists } from "./types";
/**
* Company-scope the connector model-pool settings.
*
* "Model pool" is the per-connector list of models a user has
* enabled/disabled during onboarding (Settings → Model pool). The
* original storage put it in the key-value `settings` table under
* `disabled_models:${connectorId}` — global, not tied to any
* company. That meant deleting a company left the pool config behind,
* and creating a new company inherited the previous company's
* enabled/disabled choices.
*
* This migration moves the data to a real relational table with a
* cascade FK. Company deletion now naturally wipes the settings —
* no manual cleanup in `deleteCompany()`, no risk of drift.
*
* Existing global entries cannot be assigned to a single company
* (the constraint they were written under had none), so the
* migration drops them. Users re-select their model pool on the
* next onboarding wake. Acceptable: this data is a one-click UI
* preference, not business-critical state, and the bug report was
* literally "these carry over wrongly — clear them."
*/
export function createMigrationsV42V42(deps: MigrationDeps): Migration[] {
const { db } = deps;
return [
{
version: 42,
name: "scope_connector_model_pool_by_company",
fn: () => {
if (!tableExists(db, "connector_model_pool_settings")) {
db.exec(`
CREATE TABLE connector_model_pool_settings (
company_id TEXT NOT NULL,
connector_id TEXT NOT NULL,
disabled_models_json TEXT NOT NULL DEFAULT '[]',
updated_at TEXT NOT NULL,
PRIMARY KEY (company_id, connector_id),
FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_connector_model_pool_company
ON connector_model_pool_settings(company_id);
`);
log.info("[migration v42] created connector_model_pool_settings");
}
// Purge stale global keys. Prefix scan is enough — both the
// key format (`disabled_models:<connectorId>`) and the
// semantics (one per connector) mean dropping them all is the
// correct reset.
const deleted = db
.prepare("DELETE FROM settings WHERE key LIKE 'disabled_models:%'")
.run();
const changes = Number(deleted.changes);
if (changes > 0) {
log.info(`[migration v42] dropped ${changes} legacy disabled_models:* key(s) from settings`);
}
},
},
];
}
+2
View File
@@ -6,6 +6,7 @@ import { createMigrationsV35V37 } from "./migrations/v35-v37";
import { createMigrationsV38V39 } from "./migrations/v38-v39";
import { createMigrationsV40V40 } from "./migrations/v40-v40";
import { createMigrationsV41V41 } from "./migrations/v41-v41";
import { createMigrationsV42V42 } from "./migrations/v42-v42";
import {
columnExists,
nowIso,
@@ -178,6 +179,7 @@ export function runMigrations(
...createMigrationsV38V39(deps),
...createMigrationsV40V40(deps),
...createMigrationsV41V41(deps),
...createMigrationsV42V42(deps),
];
for (const migration of migrations) {
+43 -9
View File
@@ -77,22 +77,56 @@ export function buildSettingsMethods(
return Number.isFinite(parsed) && parsed >= 1 ? parsed : 90;
},
getDisabledModels(connectorId: string): Array<{ id: string; label: string }> {
const raw = getSetting(`disabled_models:${connectorId}`);
if (!raw) return [];
/**
* Per-(company, connector) disabled model list.
*
* Pre-v42 the key-value `settings` table stored one global entry
* per connector (`disabled_models:${connectorId}`). That let the
* setting leak across companies — deleting a company did not
* clear the pool config, and new companies inherited the old
* selections. v42 moved the data to `connector_model_pool_settings`
* with `company_id` in the primary key and `ON DELETE CASCADE`
* from companies, so company removal wipes pool config by
* construction.
*/
getDisabledModels(companyId: string, connectorId: string): Array<{ id: string; label: string }> {
const row = getDb()
.prepare(
"SELECT disabled_models_json AS json FROM connector_model_pool_settings WHERE company_id = ? AND connector_id = ?",
)
.get(companyId, connectorId) as { json: string } | undefined;
if (!row) return [];
try {
return JSON.parse(raw);
return JSON.parse(row.json);
} catch {
return raw.split(",").filter(Boolean).map((id) => ({ id, label: id }));
return [];
}
},
setDisabledModels(connectorId: string, models: Array<{ id: string; label: string }>) {
setSetting(`disabled_models:${connectorId}`, JSON.stringify(models));
setDisabledModels(
companyId: string,
connectorId: string,
models: Array<{ id: string; label: string }>,
) {
const ts = new Date().toISOString();
getDb()
.prepare(
`INSERT INTO connector_model_pool_settings (company_id, connector_id, disabled_models_json, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(company_id, connector_id) DO UPDATE SET
disabled_models_json = excluded.disabled_models_json,
updated_at = excluded.updated_at`,
)
.run(companyId, connectorId, JSON.stringify(models), ts);
},
hasModelPoolSettings(connectorId: string): boolean {
return getSetting(`disabled_models:${connectorId}`) !== null;
hasModelPoolSettings(companyId: string, connectorId: string): boolean {
const row = getDb()
.prepare(
"SELECT 1 AS found FROM connector_model_pool_settings WHERE company_id = ? AND connector_id = ? LIMIT 1",
)
.get(companyId, connectorId) as { found: number } | undefined;
return !!row;
},
getLastBudgetResetMonth(companyId: string): string | null {