Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
fix: allow editing existing subscription model selections (#30)
澄潭cfadc8c53f9e
diff --git a/apps/desktop/src/features/device-scan/DeviceScanList.tsx b/apps/desktop/src/features/device-scan/DeviceScanList.tsxindex df130b03..f5ece81e 100644--- a/apps/desktop/src/features/device-scan/DeviceScanList.tsx+++ b/apps/desktop/src/features/device-scan/DeviceScanList.tsx@@ -137,6 +137,7 @@ export function DeviceScanList({<p>{repairing ? text('重新检查当前订阅登录', 'Check the current subscription sign-in again') : candidate.existing_source_id ? text('已接入,可以在模型页查看', 'Connected. View it on the Models page') : text('已发现本机登录', 'Local sign-in found')}</p></div><button className={`btn${repairing || !candidate.existing_source_id ? ' btn-primary' : ''}`} type="button" disabled={!trustedAuthority && (repairing || !candidate.existing_source_id)} onClick={() => repairing || !candidate.existing_source_id ? onOpenSubscription(candidate) : onViewConnectedSubscription(candidate)}>{repairing ? text('检查', 'Check') : candidate.existing_source_id ? text('查看', 'View') : text('接入', 'Connect')}</button>+ {candidate.existing_source_id && !repairing && <button className="btn" type="button" disabled={!trustedAuthority} onClick={() => onOpenSubscription(candidate)}>{text('调整模型', 'Choose models')}</button>}</div>;})}{!subscriptions.length && !subscriptionScanFailed && !subscriptionRuntimeUnavailable && <p className="oc-meta" role="status">{text('没有发现可复用的 Codex 订阅。', 'No reusable Codex subscription was found.')}</p>}diff --git a/apps/desktop/src/features/subscriptions/model.ts b/apps/desktop/src/features/subscriptions/model.tsindex 6965b50c..c61d3260 100644--- a/apps/desktop/src/features/subscriptions/model.ts+++ b/apps/desktop/src/features/subscriptions/model.ts@@ -49,6 +49,18 @@ export function canSave(candidate: SubscriptionCandidate, enable: boolean, selecreturn selected.size > 0;}+export function selectionRows(candidate: SubscriptionCandidate, selected: ReadonlySet<string>, saved: readonly { model_ref: string; display_name: string }[] = []) {+ const rows = candidate.models.map(model => ({+ model_ref: model.model_ref, display_name: model.display_name, selectable: model.selectable, missing: false,+ }));+ for (const ref of selected) {+ if (!rows.some(model => model.model_ref === ref)) {+ rows.push({ model_ref: ref, display_name: saved.find(model => model.model_ref === ref)?.display_name ?? ref, selectable: false, missing: true });+ }+ }+ return rows;+}+export type CloseAction =| { kind: 'none' }| { kind: 'cancel_a'; operation_id: string }diff --git a/apps/desktop/src/product/ModelManagementPage.tsx b/apps/desktop/src/product/ModelManagementPage.tsxindex 76373106..2c61559c 100644--- a/apps/desktop/src/product/ModelManagementPage.tsx+++ b/apps/desktop/src/product/ModelManagementPage.tsx@@ -38,7 +38,7 @@ import type {SubscriptionCandidate,SubscriptionCheckResult,} from '../features/subscriptions/types';-import { canSave as canSaveSubscription, saveFailureDefinitelyPreAdmission, saveIntent, validatedSubscriptionCandidate } from '../features/subscriptions/model';+import { canSave as canSaveSubscription, saveFailureDefinitelyPreAdmission, saveIntent, selectionRows, validatedSubscriptionCandidate } from '../features/subscriptions/model';import { safeDiagnosticCode } from '../error-code';type SubscriptionSaveSelection = {@@ -873,7 +873,6 @@ export function ModelManagementPage({? validatedSubscriptionCandidate(selectedSubscription, selectedSubscriptionCheck): null;const effectiveSubscription = validatedSubscription ?? selectedSubscription;- const subscriptionModels = effectiveSubscription?.models ?? [];const selectableSubscriptionModels = effectiveSubscription?.models.filter(model => model.selectable) ?? [];const selectedSubscriptionModels = new Set(effectiveSubscription? (subscriptionSelections[effectiveSubscription.candidate.candidate_ref]@@ -881,6 +880,10 @@ export function ModelManagementPage({? repairingSource?.models.map(model => model.model_ref) ?? []: selectableSubscriptionModels.map(model => model.model_ref))): []);+ const savedSubscriptionSource = management?.sources.find(source => source.source_id === selectedSubscription?.existing_source_id);+ const subscriptionModels = effectiveSubscription+ ? selectionRows(effectiveSubscription, selectedSubscriptionModels, savedSubscriptionSource?.models)+ : [];const subscriptionChecking = subscriptionAction === 'checking';const subscriptionWorking = subscriptionLoading || subscriptionChecking || subscriptionAction === 'saving';const subscriptionReady = Boolean(validatedSubscription);@@ -906,14 +909,11 @@ export function ModelManagementPage({function openSubscription(candidate: SubscriptionCandidate) {returnToScanList();setSelectedSubscriptionRef(candidate.candidate.candidate_ref);- const repairingModelRefs = repairingSource- && candidate.existing_source_id === repairingSource.source_id- ? repairingSource.models.map(model => model.model_ref)- : null;- if (repairingModelRefs) {+ const savedSource = management?.sources.find(source => source.source_id === candidate.existing_source_id);+ if (savedSource) {setSubscriptionSelections(current => ({...current,- [candidate.candidate.candidate_ref]: repairingModelRefs,+ [candidate.candidate.candidate_ref]: savedSource.models.map(model => model.model_ref),}));}setSubscriptionError(null);@@ -1048,10 +1048,12 @@ export function ModelManagementPage({<div className="oc-status-row"><BrandIcon kind="codex" label="Codex" /><div className="row-main"><strong>{effectiveSubscription.display_name}</strong><p>{language === 'zh' ? '复用本机登录,无需复制订阅凭据。' : 'Reuse the local sign-in without copying credentials.'}</p></div>{subscriptionReady && <span className="badge good">{language === 'zh' ? '可用' : 'Ready'}</span>}</div>{subscriptionReady && repairingSelectedSubscription? <p className="oc-meta">{language === 'zh' ? '将保留原有模型、绑定和路由,仅更新当前订阅授权与可执行资格。' : 'Existing models, bindings, and routes will be retained; only current subscription access and execution eligibility will be updated.'}</p>- : subscriptionReady ? subscriptionModels.length === 1 && selectableSubscriptionModels.length === 1- ? <p className="oc-meta">{language === 'zh' ? '检查通过,可接入以下模型:' : 'Check passed. Available model: '} {selectableSubscriptionModels[0].display_name}</p>- : subscriptionModels.length- ? <><p className="oc-meta">{language === 'zh' ? '已读取此账号可见的模型。选择资料完整、可接入路由的模型。' : 'Models visible to this account were loaded. Select models with complete routing data.'}</p><div className="v3-catalog">{subscriptionModels.map(model => <label className="check-row" key={model.model_ref}><input type="checkbox" disabled={!trustedAuthority || !model.selectable} checked={selectedSubscriptionModels.has(model.model_ref)} onChange={() => toggleSubscriptionModel(model.model_ref)} /><div><strong>{model.display_name}</strong>{!model.selectable && <span>{language === 'zh' ? '账号可见 · 能力资料待补充,暂不能用于路由' : 'Visible to this account · capability data pending; not yet routable'}</span>}</div></label>)}</div></>+ : subscriptionReady ? subscriptionModels.length+ ? <><p className="oc-meta">{language === 'zh' ? '已读取此账号可见的模型。选择资料完整、可接入路由的模型。' : 'Models visible to this account were loaded. Select models with complete routing data.'}</p><div className="v3-catalog">{subscriptionModels.map(model => <label className="check-row" key={model.model_ref}><input type="checkbox" disabled={!trustedAuthority || (!model.selectable && !selectedSubscriptionModels.has(model.model_ref))} checked={selectedSubscriptionModels.has(model.model_ref)} onChange={() => toggleSubscriptionModel(model.model_ref)} /><div><strong>{model.display_name}</strong>{!model.selectable && <span>{model.missing+ ? (language === 'zh' ? '已不在当前订阅目录,可取消选择' : 'No longer in the subscription directory; uncheck to remove')+ : selectedSubscriptionModels.has(model.model_ref)+ ? (language === 'zh' ? '当前不可用,可取消选择' : 'Currently unavailable; uncheck to remove')+ : (language === 'zh' ? '账号可见 · 能力资料待补充,暂不能用于路由' : 'Visible to this account · capability data pending; not yet routable')}</span>}</div></label>)}</div></>: <p className="oc-meta">{language === 'zh' ? '检查已完成,但没有可接入的模型。' : 'The check completed, but no connectable model was found.'}</p>: <p className="oc-meta">{language === 'zh' ? '检查会使用这项本机订阅验证连接;保存后才加入模型列表。' : 'The check uses this local subscription to verify the connection. Save it to add the model.'}</p>}</div> : <DeviceScanListdiff --git a/apps/desktop/tests/subscriptions-state.test.mjs b/apps/desktop/tests/subscriptions-state.test.mjsindex c944109c..a5f6c996 100644--- a/apps/desktop/tests/subscriptions-state.test.mjs+++ b/apps/desktop/tests/subscriptions-state.test.mjs@@ -8,6 +8,7 @@ import {isCurrentResult,saveFailureDefinitelyPreAdmission,saveIntent,+ selectionRows,statusText,validatedSubscriptionCandidate,} from '../src/features/subscriptions/model.ts';@@ -146,3 +147,41 @@ test('inventory-only rows stay visible but cannot be selected or saved', () => {assert.equal(canSave(checked, true, new Set(['model/gpt', 'model/unknown'])), false);assert.equal(canSave(checked, true, new Set()), false);});++test('an existing checked subscription permits explicit addition and removal, not unverified additions', () => {+ const checked = candidate({ existing_source_id: 'source/subscription' });+ checked.models.push({+ model_ref: 'model/new', upstream_model_id: 'new', display_name: 'New',+ membership: 'catalog', selectable: true,+ });+ assert.equal(canSave(checked, true, new Set(['model/gpt', 'model/new'])), true);+ assert.equal(canSave(checked, true, new Set(['model/new'])), true);+ checked.models[1].selectable = false;+ assert.equal(canSave(checked, true, new Set(['model/gpt', 'model/new'])), false);+ assert.equal(canSave(checked, true, new Set(['model/missing'])), false);+});++test('a saved model missing from the checked directory stays visible until explicitly removed', () => {+ const checked = candidate({ existing_source_id: 'source/subscription' });+ const selected = new Set(['model/gpt', 'model/retired']);+ const saved = [{ model_ref: 'model/retired', display_name: 'Saved retired model' }];+ assert.equal(canSave(checked, true, selected), false);+ assert.deepEqual(selectionRows(checked, selected, saved).at(-1), {+ model_ref: 'model/retired', display_name: 'Saved retired model', selectable: false, missing: true,+ });+ selected.delete('model/retired');+ assert.equal(selectionRows(checked, selected, saved).length, 1);+ assert.equal(canSave(checked, true, selected), true);+});++test('a disappeared unsaved selection is also removable without granting eligibility', () => {+ const checked = candidate();+ const selected = new Set(['model/gpt', 'model/no-longer-listed']);+ const missing = selectionRows(checked, selected).at(-1);+ assert.equal(missing.model_ref, 'model/no-longer-listed');+ assert.equal(missing.selectable, false);+ assert.equal(missing.missing, true);+ assert.equal(canSave(checked, true, selected), false);+ selected.delete(missing.model_ref);+ assert.equal(canSave(checked, true, selected), true);+});diff --git a/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs b/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjsindex 8f57a2e6..9010bc2f 100644--- a/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs+++ b/apps/desktop/tests/v3/browser/subscription-repair-scenarios.mjs@@ -219,6 +219,68 @@ const scenarios = [assert(!document.querySelector('[role="alert"]'), 'Unknown save falsely reported failed');assert(c().recoveryRefreshes > 0, 'Unknown operation not handed to recovery');}],+ ['adjustment can remove a saved model absent from the current directory and add a new model', async () => {+ await fresh(control => {+ const source = control.management.sources[0];+ const template = source.models[0];+ source.models = [+ { ...template, model_ref: 'model/retired', display_name: 'Saved retired model' },+ { ...template, model_ref: 'model/matched', display_name: 'Matched model' },+ ];+ control.subscriptions = [{ ...control.pending, existing_source_id: source.source_id }];+ const checked = { ...control.checked, existing_source_id: source.source_id, models: [+ control.checked.models[0],+ { ...control.checked.models[0], model_ref: 'model/new', display_name: 'New model' },+ ] };+ control.handlers.check_subscription = () => {+ control.subscriptions = [checked];+ control.result = { ...control.verified, checked_candidate: checked };+ return control.result;+ };+ });+ await scan(); await click('调整模型'); await click('检查订阅');+ await until(() => button('保存接入'), 'adjustment checked');+ const box = name => [...document.querySelectorAll('.v3-catalog .check-row')].find(row => row.textContent.includes(name))?.querySelector('input');+ assert(box('Saved retired model')?.checked && !box('Saved retired model').disabled, 'Missing saved model has no removal control');+ assert(box('Matched model').checked && !box('New model').checked, 'Adjustment changed saved selections automatically');+ assert(button('保存接入').disabled, 'Missing model can be submitted');+ box('Saved retired model').click(); await tick();+ assert(!box('Saved retired model'), 'Removed missing model remains selected');+ box('New model').click(); await tick();+ await click('保存接入');+ await until(() => calls('apply_compute_save').length === 1, 'adjustment applied');+ assert(JSON.stringify(calls('preview_compute_save')[0].payload.change.selected_model_refs) === '["model/matched","model/new"]', 'Explicit adjustment submitted stale or automatic selections');+ }],+ ['adjustment can deselect a listed unavailable model but cannot select an unavailable model', async () => {+ await fresh(control => {+ const source = control.management.sources[0];+ const template = source.models[0];+ source.models = [+ { ...template, model_ref: 'model/unavailable', display_name: 'Unavailable saved model' },+ { ...template, model_ref: 'model/matched', display_name: 'Matched model' },+ ];+ control.subscriptions = [{ ...control.pending, existing_source_id: source.source_id }];+ const checked = { ...control.checked, existing_source_id: source.source_id, models: [+ { ...control.checked.models[0], model_ref: 'model/unavailable', display_name: 'Unavailable saved model', selectable: false },+ control.checked.models[0], control.checked.models[1],+ ] };+ control.handlers.check_subscription = () => {+ control.subscriptions = [checked];+ control.result = { ...control.verified, checked_candidate: checked };+ return control.result;+ };+ });+ await scan(); await click('调整模型'); await click('检查订阅');+ await until(() => button('保存接入'), 'unavailable adjustment checked');+ const box = name => [...document.querySelectorAll('.v3-catalog .check-row')].find(row => row.textContent.includes(name))?.querySelector('input');+ assert(box('Unavailable saved model')?.checked && !box('Unavailable saved model').disabled, 'Unavailable saved model cannot be deselected');+ assert(box('Inventory only').disabled && !box('Inventory only').checked, 'Unverified addition was enabled');+ box('Unavailable saved model').click(); await tick();+ assert(!box('Unavailable saved model').checked && box('Unavailable saved model').disabled, 'Unavailable model can be selected again');+ await click('保存接入');+ await until(() => calls('apply_compute_save').length === 1, 'unavailable adjustment applied');+ assert(JSON.stringify(calls('preview_compute_save')[0].payload.change.selected_model_refs) === '["model/matched"]', 'Unavailable model survived the explicit removal');+ }],];export async function runSubscriptionRepairScenarios(start = 0, end = Infinity) {diff --git a/apps/desktop/tests/v3/visual/subscription-repair-active.mjs b/apps/desktop/tests/v3/visual/subscription-repair-active.mjsnew file mode 100644index 00000000..8823c44b--- /dev/null+++ b/apps/desktop/tests/v3/visual/subscription-repair-active.mjs@@ -0,0 +1,24 @@+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { connectPage, evaluate, navigate, waitFor } from './cdp-client.mjs';++const port = Number(process.argv[2]);+const baseUrl = process.argv[3];+const outputRoot = process.argv[4] && path.resolve(process.argv[4]);+if (!Number.isInteger(port) || !baseUrl || !outputRoot) {+ throw new Error('Usage: node subscription-repair-active.mjs <cdp-port> <base-url> <output-directory>');+}+const client = await connectPage(port);+try {+ await navigate(client, new URL('subscription-repair.html', baseUrl).href, { width: 1280, height: 900 });+ await waitFor(client, 'Boolean(window.subscriptionRepair)', { timeout: 7000 });+ const report = await evaluate(client, "import('/subscription-repair-scenarios.mjs').then(module => module.runSubscriptionRepairScenarios())");+ for (const item of report.results) {+ process.stdout.write(`${item.state}: ${item.name}${item.error ? ` · ${item.error}` : ''}\n`);+ }+ await mkdir(outputRoot, { recursive: true });+ await writeFile(path.join(outputRoot, 'subscription-repair-report.json'), `${JSON.stringify(report, null, 2)}\n`);+ if (report.tests !== 15 || report.failed > 0) process.exitCode = 1;+} finally {+ client.close();+}diff --git a/crates/application/src/compute_management/mutations.rs b/crates/application/src/compute_management/mutations.rsindex 1fd96653..e3646970 100644--- a/crates/application/src/compute_management/mutations.rs+++ b/crates/application/src/compute_management/mutations.rs@@ -137,8 +137,14 @@ where&& candidate.producer== hiroute_application_api::ComputeCandidateProducerV2::Cpa&& candidate.existing_source_id.as_deref()- == Some(source.source_id.as_str()) =>+ == Some(source.source_id.as_str())+ && change+ .selected_model_refs+ .iter()+ .eq(source.models.iter().map(|model| &model.model_ref)) =>{+ // An unchanged recheck preserves lost members as unavailable. Explicit+ // selection edits use ordinary candidate validation instead of retention.ModelSelectionPolicy::RetainSubscriptionMembers}_ => policy,diff --git a/crates/diagnostics/tests/worker_probe_progress.rs b/crates/diagnostics/tests/worker_probe_progress.rsindex ca0dfb36..6ca2e190 100644--- a/crates/diagnostics/tests/worker_probe_progress.rs+++ b/crates/diagnostics/tests/worker_probe_progress.rs@@ -105,6 +105,16 @@ fn a_running_worker_step_republishes_and_never_clears_the_startup_stage() {WorkerStageKind::ProbeLoad,WorkerStageOutcome::Completed,);+ // Shutdown deliberately bounds its wait for the writer; it is not a persistence+ // barrier on a slow filesystem. Observe the real end before checking its ordering.+ assert!(+ wait_until(Instant::now() + Duration::from_secs(12), || {+ worker_steps(&log, WorkerStageKind::ProbeLoad)+ .iter()+ .any(|step| step.outcome == WorkerStageOutcome::Completed)+ }),+ "the real step end must be written before validating the lifecycle"+ );runtime.shutdown();let steps = worker_steps(&log, WorkerStageKind::ProbeLoad);diff --git a/crates/local-storage/src/control/compute/management/tests.rs b/crates/local-storage/src/control/compute/management/tests.rsindex bcaaca25..fb2e7c0e 100644--- a/crates/local-storage/src/control/compute/management/tests.rs+++ b/crates/local-storage/src/control/compute/management/tests.rs@@ -31,6 +31,8 @@ use hiroute_domain::{use super::super::super::ControlStore;use crate::{LocalSecretStore, LocalStorageSet, RuntimeStore};+mod subscription_selection;+struct ProtectedInput;impl ProtectedInputPort for ProtectedInput {diff --git a/crates/local-storage/src/control/compute/management/tests/subscription_selection.rs b/crates/local-storage/src/control/compute/management/tests/subscription_selection.rsnew file mode 100644index 00000000..821c88d4--- /dev/null+++ b/crates/local-storage/src/control/compute/management/tests/subscription_selection.rs@@ -0,0 +1,273 @@+use super::*;+use hiroute_application::compute_management::ComputeSubscriptionMaintenanceScopeV1;+use hiroute_application_api::{ComputeValidationRefV2, OperationReferenceV1};+use hiroute_domain::ComputeManagementRepositoryPort;++fn subscription(candidate_ref: &str) -> ComputeCandidateFactsV2 {+ let mut facts = candidate(candidate_ref, "unused-subscription-input");+ let digest = hiroute_domain::CanonicalDigest::of_bytes(candidate_ref.as_bytes());+ let validation = ComputeValidationRefV2 {+ approval_operation: OperationReferenceV1 {+ operation_id: format!("op_{}", &digest.as_str()[7..39]),+ state: "succeeded".into(),+ sequence: 1,+ cancellable: false,+ },+ validation_ref: "validation/subscription".into(),+ validation_revision: 1,+ };+ facts.producer = ComputeCandidateProducerV2::Cpa;+ facts.lineage_ref = "lineage/subscription".into();+ facts.provenance = ComputeCandidateProvenanceV2::ConnectorOwned {+ connector_id: "connector/cpa".into(),+ account_ref: "account/subscription".into(),+ };+ facts.authentication = Some(GatewayAuthenticationSemanticsV1::Bearer);+ facts.native_recheck = None;+ facts.credential_binding = ComputeCredentialBindingV2::CpaOwned {+ account_ref: "account/subscription".into(),+ validation: validation.clone(),+ };+ facts.validation = Some(validation);+ for model in &mut facts.models {+ model.membership = ComputeModelMembershipV2::Observed;+ model.capabilities.tool.basis = ComputeCandidateFactBasisV2::ConnectorVerified;+ model.capabilities.vision.basis = ComputeCandidateFactBasisV2::ConnectorVerified;+ model.capabilities.streaming.basis = ComputeCandidateFactBasisV2::ConnectorVerified;+ model.capabilities.context_tokens.basis = ComputeCandidateFactBasisV2::ConnectorVerified;+ model.capabilities.max_output_tokens.basis = ComputeCandidateFactBasisV2::ConnectorVerified;+ model.capabilities.native_reasoning.basis = ComputeCandidateFactBasisV2::ConnectorVerified;+ }+ facts+}++fn change(+ stores: &LocalStorageSet,+ facts: &ComputeCandidateFactsV2,+ selected: &[&str],+) -> ComputeManagementChangeV2 {+ ComputeManagementChangeV2 {+ schema: "hiroute.compute-management-change/v2".into(),+ subject: ComputeManagementSubjectV2::Candidate {+ candidate: facts.candidate.clone(),+ },+ expected_revisions: stores+ .control()+ .compute_management_snapshot(&WorkspaceId::default())+ .unwrap()+ .revisions,+ selected_model_refs: selected.iter().map(|model| (*model).into()).collect(),+ intent: ComputeManagementIntentV2::SaveReady,+ key_edits: Vec::new(),+ validation: facts.validation.clone(),+ }+}++fn save(+ stores: &LocalStorageSet,+ registry: &TrustedComputeCandidateRegistry,+ facts: &ComputeCandidateFactsV2,+ selected: &[&str],+ key: &str,+) -> hiroute_domain::ComputeManagementSourceV2 {+ // This storage test starts at verified subscription facts. Admission still uses+ // the real durable handoff and transaction; the daemon tests cover the check.+ let validation = facts.validation.as_ref().unwrap();+ stores.control().with_connection(|connection| {+ connection+ .execute(+ "INSERT INTO operations(+ operation_id,workspace_id,principal,operation_kind,idempotency_key,+ request_digest,accepted_change_digest,state,generation,operation_json,+ created_at,updated_at+ ) VALUES(?1,'personal/default','local-control','ApplySubscriptionCheck',?2,+ 'sha256:request','sha256:accepted','succeeded',1,'{}',1,1)",+ rusqlite::params![validation.approval_operation.operation_id, key],+ )+ .unwrap();+ connection+ .execute(+ "INSERT INTO compute_subscription_validations(+ operation_id,candidate_ref,candidate_revision,record_json,state,updated_at+ ) VALUES(?1,?2,?3,?4,'verified',1)",+ rusqlite::params![+ validation.approval_operation.operation_id,+ facts.candidate.candidate_ref,+ facts.candidate.candidate_revision,+ serde_json::json!({ "validation": validation }).to_string(),+ ],+ )+ .unwrap();+ });+ registry.register_compute_candidate(facts.clone()).unwrap();+ let input = ProtectedInput;+ let planner =+ ComputeManagementPlanner::new(registry, stores.control(), stores.secrets(), &input);+ let preview = planner.preview(change(stores, facts, selected)).unwrap();+ let runtime = TransactionRuntime::default();+ let external = NoExternal;+ let coordinator = TransactionCoordinator::new(+ stores.control(),+ stores.secrets(),+ stores.runtime(),+ &external,+ &input,+ &runtime,+ );+ coordinator.reconcile_startup_and_open().unwrap();+ apply_preview(+ stores,+ &planner,+ &coordinator,+ &WorkspaceId::default(),+ preview,+ key,+ );+ let snapshot = stores+ .control()+ .compute_management_snapshot(&WorkspaceId::default())+ .unwrap();+ assert_eq!(snapshot.sources.len(), 1);+ snapshot.sources.into_iter().next().unwrap()+}++#[test]+fn subscription_explicit_selection_adds_and_removes_models_on_the_same_source() {+ let directory = tempdir().unwrap();+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();+ let registry = TrustedComputeCandidateRegistry::new();+ let first = save(+ &stores,+ ®istry,+ &subscription("candidate/first"),+ &["model/one"],+ "first",+ );+ let mut edited = subscription("candidate/add");+ edited.existing_source_id = Some(first.source_id.clone());+ let added = save(+ &stores,+ ®istry,+ &edited,+ &["model/one", "model/two"],+ "add",+ );+ assert_eq!(added.source_id, first.source_id);+ assert_eq!(added.lineage_digest, first.lineage_digest);+ assert_eq!(added.provenance, first.provenance);+ assert_eq!(added.revision, first.revision + 1);+ assert_eq!(added.models.len(), 2);+ assert_eq!(added.models[0], first.models[0]);+ assert!(added.models.iter().all(|model| model.execution_eligible));+ assert!(added.credentials.is_empty());+ let second_binding = added.models[1].binding_id.clone();++ let mut edited = subscription("candidate/remove");+ edited.existing_source_id = Some(first.source_id.clone());+ let removed = save(&stores, ®istry, &edited, &["model/two"], "remove");+ assert_eq!(removed.source_id, first.source_id);+ assert_eq!(removed.revision, added.revision + 1);+ assert_eq!(removed.models.len(), 1);+ assert_eq!(removed.models[0].model_ref, "model/two");+ assert_eq!(removed.models[0].binding_id, second_binding);++ drop(stores);+ let reopened = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();+ let persisted = reopened+ .control()+ .compute_management_source(&removed.source_id)+ .unwrap()+ .unwrap();+ assert_eq!(persisted, removed);+}++#[test]+fn subscription_explicit_selection_rejects_ineligible_and_unknown_models_without_writes() {+ let directory = tempdir().unwrap();+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();+ let registry = TrustedComputeCandidateRegistry::new();+ let first = save(+ &stores,+ ®istry,+ &subscription("candidate/first"),+ &["model/one"],+ "first",+ );+ let mut edited = subscription("candidate/invalid-add");+ edited.existing_source_id = Some(first.source_id.clone());+ edited.models[1].selectable = false;+ edited.models[1].reason = Some("model_not_allowed".into());+ registry.register_compute_candidate(edited.clone()).unwrap();+ let input = ProtectedInput;+ let planner =+ ComputeManagementPlanner::new(®istry, stores.control(), stores.secrets(), &input);+ let before = stores+ .control()+ .compute_management_snapshot(&WorkspaceId::default())+ .unwrap();+ for selected in [+ vec!["model/one", "model/two"],+ vec!["model/unknown"],+ vec!["model/one", "model/one"],+ ] {+ assert!(matches!(+ planner.preview(change(&stores, &edited, &selected)),+ Err(ComputeManagementPlanningErrorV2::ModelNotSelectable)+ ));+ }+ let after = stores+ .control()+ .compute_management_snapshot(&WorkspaceId::default())+ .unwrap();+ assert_eq!(after, before);+}++#[test]+fn subscription_recheck_and_background_refresh_retain_membership_when_rights_change() {+ let directory = tempdir().unwrap();+ let stores = LocalStorageSet::open_for_daemon_startup(directory.path()).unwrap();+ let registry = TrustedComputeCandidateRegistry::new();+ let first = save(+ &stores,+ ®istry,+ &subscription("candidate/first"),+ &["model/one"],+ "first",+ );+ let mut refreshed = subscription("candidate/refresh");+ refreshed.existing_source_id = Some(first.source_id.clone());+ refreshed.models[0].selectable = false;+ refreshed.models[0].reason = Some("model_not_allowed".into());+ registry+ .register_compute_candidate(refreshed.clone())+ .unwrap();+ let input = ProtectedInput;+ let planner =+ ComputeManagementPlanner::new(®istry, stores.control(), stores.secrets(), &input);+ let scope = ComputeSubscriptionMaintenanceScopeV1 {+ source_id: first.source_id.clone(),+ expected_source_revision: first.revision,+ };+ assert!(+ planner+ .preview_subscription_maintenance(change(&stores, &refreshed, &["model/one"]), &scope)+ .is_ok()+ );+ for selected in [vec!["model/one", "model/two"], vec!["model/two"]] {+ assert!(matches!(+ planner+ .preview_subscription_maintenance(change(&stores, &refreshed, &selected), &scope),+ Err(ComputeManagementPlanningErrorV2::ModelNotSelectable)+ ));+ }+ let retained = save(&stores, ®istry, &refreshed, &["model/one"], "recheck");+ assert_eq!(retained.source_id, first.source_id);+ assert_eq!(retained.models.len(), 1);+ assert_eq!(retained.models[0].binding_id, first.models[0].binding_id);+ assert!(!retained.models[0].execution_eligible);+ assert!(+ compile_compute_management_source(&retained)+ .unwrap()+ .is_empty()+ );+}