diff --git a/internal/device/mbn_policy_test.go b/internal/device/mbn_policy_test.go new file mode 100644 index 00000000..293a37e0 --- /dev/null +++ b/internal/device/mbn_policy_test.go @@ -0,0 +1,100 @@ +package device + +import ( + "context" + "errors" + "testing" + + "github.com/yibaiba/hideck/internal/backend" + "github.com/yibaiba/hideck/internal/cardpolicy" + "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/mbn" +) + +type fixedMBNPolicyStore struct{ mbn.Store } + +func (fixedMBNPolicyStore) Policies(context.Context) ([]mbn.Policy, error) { + return []mbn.Policy{{Key: "sim:card", Mode: "fixed", Profile: "B", Model: "EC20F", Firmware: "expected"}}, nil +} + +type unavailableMBNGateway struct{ onOpen func() } + +func (unavailableMBNGateway) Identity(context.Context, string) (mbn.Owner, error) { + return mbn.Owner{}, nil +} +func (g unavailableMBNGateway) Open(context.Context, string, bool) (mbn.Session, error) { + if g.onOpen != nil { + g.onOpen() + } + return nil, errors.New("MBN query unsupported on replacement modem") +} + +func mbnPolicyTestDevice() (*Pool, *Worker, *workerStatusBackendStub) { + p := &Pool{ctx: context.Background()} + p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ICCID: "card", PhoneMode: PhoneModeWiFi, AirplaneEnabled: true}}) + stub := &workerStatusBackendStub{opMode: backend.ModeOnline} + w := &Worker{ID: "d", Pool: p, Backend: stub, Config: config.DeviceConfig{PhoneMode: PhoneModeVoLTE}, stop: make(chan struct{})} + w.state.Identity.ICCID = "card" + w.state.Identity.IMEI = "imei" + w.state.Identity.IMSI = "234150000000001" + w.state.Identity.Ready = true + p.workers = map[string]*Worker{"d": w} + p.SetMBNService(mbn.New(mbn.Options{Context: p.ctx, Store: fixedMBNPolicyStore{}, Gateway: unavailableMBNGateway{}})) + return p, w, stub +} + +func TestMBNFailureMustNotKeepPreviousSIMRadioPolicy(t *testing.T) { + p, w, stub := mbnPolicyTestDevice() + p.SetMBNService(mbn.New(mbn.Options{Context: p.ctx, Store: fixedMBNPolicyStore{}, Gateway: unavailableMBNGateway{onOpen: func() { + if !w.Config.AirplaneEnabled || stub.opMode != backend.ModeRFOff { + t.Error("MBN queried before applying the new SIM's RF restriction") + } + }}})) + result := p.resolveAndApplyPolicy(w, "identity_ready") + if !w.Config.AirplaneEnabled || !w.cellularRadioIsSuppressed() || stub.opMode != backend.ModeRFOff { + t.Fatalf("new SIM RF-off policy skipped; previous mode=%s airplane=%v result=%+v", w.Config.PhoneMode, w.Config.AirplaneEnabled, result) + } + if result.Err == nil || result.Applied || result.Reason != "mbn_policy" { + t.Fatalf("MBN failure was hidden: %+v", result) + } +} + +func TestMBNFailureDoesNotStartDependentCellularServices(t *testing.T) { + p, w, stub := mbnPolicyTestDevice() + w.Config = config.DeviceConfig{PhoneMode: PhoneModeWiFi, AirplaneEnabled: true} + stub.opMode = backend.ModeRFOff + p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ICCID: "card", PhoneMode: PhoneModeVoLTE, VoWiFiEnabled: true, NetworkEnabled: true}}) + result := p.resolveAndApplyPolicy(w, "identity_ready") + if result.Err == nil || result.Applied || w.Config.PhoneMode != PhoneModeVoLTE { + t.Fatalf("policy or error lost: %+v config=%+v", result, w.Config) + } + assertNoRadioOnline(t, stub, "MBN failure") +} + +func TestMBNInspectionRechecksPolicyAndSIM(t *testing.T) { + for _, change := range []string{"policy", "sim"} { + t.Run(change, func(t *testing.T) { + p, w, stub := mbnPolicyTestDevice() + p.SetMBNService(mbn.New(mbn.Options{Context: p.ctx, Store: fixedMBNPolicyStore{}, Gateway: unavailableMBNGateway{onOpen: func() { + transition := p.policyTransitionFor(w.ID) + if !transition.TryLock() { + t.Error("inspection held transition lock; real gateway would deadlock") + return + } + defer transition.Unlock() + if change == "policy" { + w.Config.PhoneMode = PhoneModeModemVoice + } else { + w.cacheMu.Lock() + w.state.Identity.Generation++ + w.cacheMu.Unlock() + } + }}})) + result := p.resolveAndApplyPolicy(w, "identity_ready") + if result.Err == nil || result.Applied || result.Reason == "mbn_policy" { + t.Fatalf("stale policy resumed: %+v", result) + } + assertNoRadioOnline(t, stub, "stale policy") + }) + } +} diff --git a/internal/device/policy_apply.go b/internal/device/policy_apply.go index 5f997f19..47835454 100644 --- a/internal/device/policy_apply.go +++ b/internal/device/policy_apply.go @@ -1,6 +1,7 @@ package device import ( + "errors" "time" "github.com/yibaiba/hideck/pkg/logger" @@ -35,11 +36,6 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR if ownerErr != nil { return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: ownerErr} } - if reason != "mbn_operation_finished" { - if pending, err := p.reconcileMBN(worker); err != nil || pending { - return policyApplyResult{ICCID: iccid, Reason: "mbn_policy", Err: err} - } - } releaseOperation, err := p.AcquireDeviceOperation(worker.ID) if err != nil { return policyApplyResult{ICCID: iccid, Reason: "mbn_operation_active", Err: err} @@ -101,13 +97,39 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR logger.Info("已投影卡策略", "device", worker.ID, "iccid", iccid, "network", effective.NetworkEnabled, "vowifi", effective.VoWiFiEnabled, "airplane", effective.AirplaneEnabled, "reason", reason) + // Apply the current SIM's RF restrictions before inspecting or queuing MBN. + // Keep the shared operation lease while temporarily releasing the transition + // lock: inspection needs that lock, and a queued writer must wait for us. + radioSuppressed := shouldSuppressCellularRadio(effective) + if radioSuppressed { + p.enterAirplaneModeFromPolicy(worker, reason) + } + nativeEnabled := IsNativeVoLTEMode(effective.PhoneMode) && PhoneServiceEnabled(effective) && !effective.AirplaneEnabled + if !nativeEnabled && !modemVoiceHandoff { + p.stopNativeVoLTE(worker.ID, reason) + } + var mbnPending bool + var mbnErr error + if reason != "mbn_operation_finished" && p.mbnService != nil { + transition.Unlock() + mbnPending, mbnErr = p.reconcileMBN(worker) + transition.Lock() + if err := validate(); err != nil { + return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err} + } + if worker.Config != effective { + return policyApplyResult{ICCID: iccid, Reason: "policy_changed", Err: errors.New("MBN 检查期间设备策略已改变,请按当前策略重试")} + } + if (mbnPending || mbnErr != nil) && !radioSuppressed { + return policyApplyResult{ICCID: iccid, Reason: "mbn_policy", Err: mbnErr} + } + } // 三态分支:VoWiFi / 纯飞行 / 在线(含连网)。射频模式按策略真正切换, // 补齐此前“airplane 字段被投影但从不执行”的缺口。 switch { case effective.AirplaneEnabled: // 飞行优先:蜂窝软件电话可以保持开启,只关射频和流量。 - p.enterAirplaneModeFromPolicy(worker, reason) case PhoneServiceEnabled(effective) && PhoneModeCampsOnCell(effective.PhoneMode): // 蜂窝软件电话 / 原生 VoLTE:射频保持在线以驻网。网络开着才连上网数据。 p.exitAirplaneModeIfNeeded(worker, reason) @@ -130,7 +152,7 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR if err := validate(); err != nil { return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err} } - if IsNativeVoLTEMode(effective.PhoneMode) && PhoneServiceEnabled(effective) && !effective.AirplaneEnabled { + if nativeEnabled { // Carrier policy can project a software IMS mode into native VoLTE. if finishNativeTransition != nil { finishNativeTransition() @@ -139,9 +161,6 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR p.clearDesiredVoWiFiRecoverState(worker.ID) p.scheduleNativeVoLTE(worker.ID, reason) } else { - if !modemVoiceHandoff { - p.stopNativeVoLTE(worker.ID, reason) - } if PhoneServiceEnabled(effective) && !UsesModemPhoneControl(effective.PhoneMode) && !cellularSoftwarePhoneHeld(worker, pol) { p.scheduleDesiredVoWiFiRecover(worker.ID, reason, time.Now()) } else { @@ -154,5 +173,8 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR if err := p.reconcileModemVoice(worker); err != nil { return policyApplyResult{ICCID: iccid, Reason: "modem_voice_failed", Err: err} } + if mbnPending || mbnErr != nil { + return policyApplyResult{ICCID: iccid, Reason: "mbn_policy", Err: mbnErr} + } return policyApplyResult{Applied: true, ICCID: iccid, Reason: reason} } diff --git a/internal/mbn/policy.go b/internal/mbn/policy.go index 82d255ea..e2a85ac6 100644 --- a/internal/mbn/policy.go +++ b/internal/mbn/policy.go @@ -129,7 +129,12 @@ func (s *Service) Reconcile(ctx context.Context, owner Owner) (bool, error) { } else if current.AutoSel { return false, nil } - request := Request{ExpectedOwner: ¤t.Owner, RequestID: fmt.Sprintf("policy-%s-%s-%d", owner.IMEI, owner.ICCID, policy.UpdatedAt.UnixNano()), Kind: "apply", Profile: policy.Profile, Version: policy.Version, AutoSel: policy.Mode == "autosel"} + request := Request{ + ExpectedOwner: ¤t.Owner, + RequestID: fmt.Sprintf("policy-%s-%s-%s-%d-%d-%d", s.policySessionID, owner.IMEI, owner.ICCID, + owner.Generation, owner.IdentityGeneration, policy.UpdatedAt.UnixNano()), + Kind: "apply", Profile: policy.Profile, Version: policy.Version, AutoSel: policy.Mode == "autosel", + } if policy.Mode == "fixed" && !hasProfile(current, policy.Profile) { if !policy.AllowImport { return false, errors.New("策略指定的 MBN 不在模组中,且未授权自动导入") diff --git a/internal/mbn/policy_reconcile_test.go b/internal/mbn/policy_reconcile_test.go new file mode 100644 index 00000000..3fda6d52 --- /dev/null +++ b/internal/mbn/policy_reconcile_test.go @@ -0,0 +1,160 @@ +package mbn + +import ( + "context" + "errors" + "testing" +) + +func TestPolicyReappliesAfterReturningToSIM(t *testing.T) { + s, f := testService(t) + ctx := context.Background() + policy := Policy{Key: "sim:" + f.owner.ICCID, Mode: "fixed", Model: f.owner.Model, Firmware: f.owner.Firmware, Profile: "B"} + if err := s.SavePolicy(ctx, policy); err != nil { + t.Fatal(err) + } + if pending, err := s.Reconcile(ctx, f.owner); !pending || err != nil { + t.Fatalf("first pending=%v err=%v", pending, err) + } + s.Wait() + if f.active != "B" { + t.Fatalf("first did not apply: %s", f.active) + } + // Another SIM used A, then the original SIM returns with a new identity generation. + f.owner.IdentityGeneration += 2 + f.active, f.selected = "A", "A" + pending, err := s.Reconcile(ctx, f.owner) + if err != nil || !pending { + t.Fatalf("returning SIM cannot reapply: pending=%v err=%v", pending, err) + } + s.Wait() + if f.active != "B" { + t.Fatalf("returned SIM retained wrong profile %s", f.active) + } +} + +func TestPolicyFailureDoesNotRepeatInSameSession(t *testing.T) { + s, f := testService(t) + ctx := context.Background() + f.rebootErr = errors.New("reboot not confirmed") + if err := s.SavePolicy(ctx, Policy{Key: "sim:" + f.owner.ICCID, Mode: "fixed", Model: f.owner.Model, Firmware: f.owner.Firmware, Profile: "B"}); err != nil { + t.Fatal(err) + } + if pending, err := s.Reconcile(ctx, f.owner); err != nil || !pending { + t.Fatalf("pending=%v err=%v", pending, err) + } + s.Wait() + for i := 0; i < 3; i++ { + if pending, err := s.Reconcile(ctx, f.owner); pending || err == nil { + t.Fatalf("failed attempt not reported: pending=%v err=%v", pending, err) + } + } + jobs, err := s.Operations(ctx, "d") + if err != nil || len(jobs) != 1 || f.reboots != 1 { + t.Fatalf("unexpected retries: jobs=%d reboots=%d err=%v", len(jobs), f.reboots, err) + } +} + +func TestPolicyReappliesAfterServiceRestart(t *testing.T) { + s, f := testService(t) + ctx := context.Background() + if err := s.SavePolicy(ctx, Policy{Key: "sim:" + f.owner.ICCID, Mode: "fixed", Model: f.owner.Model, Firmware: f.owner.Firmware, Profile: "B"}); err != nil { + t.Fatal(err) + } + if pending, err := s.Reconcile(ctx, f.owner); !pending || err != nil { + t.Fatalf("pending=%v err=%v", pending, err) + } + s.Wait() + f.active, f.selected = "A", "A" // Another card was used while HiDeck was stopped. + restarted := New(Options{Context: s.ctx, Store: s.store, Files: s.files, Gateway: s.gateway}) + t.Cleanup(restarted.Wait) + if pending, err := restarted.Reconcile(ctx, f.owner); !pending || err != nil { + t.Fatalf("old process request reused: pending=%v err=%v", pending, err) + } + restarted.Wait() + if f.active != "B" || f.reboots != 2 { + t.Fatalf("profile=%s reboots=%d", f.active, f.reboots) + } +} + +type deadlineRegistrationSession struct { + *testSession + polls int + lastCandidateReady bool +} + +func (f *deadlineRegistrationSession) Registration(ctx context.Context) (Registration, error) { + if f.lastCandidateReady && f.active == "A" { + return Registration{Registered: true}, nil + } + f.polls++ + if f.polls >= 2 { + <-ctx.Done() + return Registration{}, ctx.Err() + } + return Registration{}, nil +} + +func TestObservationTimeoutCanReachHealthyCandidate(t *testing.T) { + s, f := testService(t) + s.gateway = registrationTestGateway{&deadlineRegistrationSession{testSession: f, lastCandidateReady: true}} + op, err := s.Start(context.Background(), "d", Request{RequestID: "trial", Kind: "trial", Candidates: []string{"B", "A"}, RegistrationSeconds: 1, StabilitySeconds: 1}) + if err != nil { + t.Fatal(err) + } + result := waitOperation(t, s, op.ID) + if result.Status != "succeeded" || len(result.Results) != 2 || result.Results[0].Passed || !result.Results[1].Passed || f.active != "A" { + t.Fatalf("healthy candidate not reached after observation timeout: %+v", result) + } +} + +type registrationTestGateway struct{ session Session } + +func (g registrationTestGateway) Open(context.Context, string, bool) (Session, error) { + return g.session, nil +} +func (g registrationTestGateway) Identity(context.Context, string) (Owner, error) { + return g.session.Owner(), nil +} + +func TestObservationTimeoutStillTriesNextCandidate(t *testing.T) { + s, f := testService(t) + s.gateway = registrationTestGateway{&deadlineRegistrationSession{testSession: f}} + op, err := s.Start(context.Background(), "d", Request{RequestID: "trial", Kind: "trial", Candidates: []string{"B", "A"}, RegistrationSeconds: 1, StabilitySeconds: 1}) + if err != nil { + t.Fatal(err) + } + result := waitOperation(t, s, op.ID) + if len(result.Results) != 2 { + t.Fatalf("observation deadline prematurely aborted remaining candidates: %+v", result) + } + if result.Status != "failed" || result.Stage != "restored" || f.active != "A" { + t.Fatalf("exhausted candidates were not restored: %+v", result) + } +} + +type failedRegistrationSession struct { + *testSession + err error +} + +func (f failedRegistrationSession) Registration(context.Context) (Registration, error) { + return Registration{}, f.err +} + +func TestTrialDoesNotAdvanceAfterRegistrationFailure(t *testing.T) { + for _, failure := range []error{ErrOwnerChanged, context.Canceled, context.DeadlineExceeded, errors.New("transport disconnected")} { + t.Run(failure.Error(), func(t *testing.T) { + s, f := testService(t) + s.gateway = registrationTestGateway{failedRegistrationSession{testSession: f, err: failure}} + op, err := s.Start(context.Background(), "d", Request{RequestID: "failure", Kind: "trial", Candidates: []string{"B", "A"}}) + if err != nil { + t.Fatal(err) + } + result := waitOperation(t, s, op.ID) + if len(result.Results) != 1 || result.Status == "succeeded" { + t.Fatalf("fatal failure advanced the trial: %+v", result) + } + }) + } +} diff --git a/internal/mbn/service.go b/internal/mbn/service.go index a22eaf99..f09a46ad 100644 --- a/internal/mbn/service.go +++ b/internal/mbn/service.go @@ -13,14 +13,15 @@ import ( ) type Service struct { - store Store - files Files - gateway Gateway - ctx context.Context - mu sync.Mutex - active map[string]string - overrides map[string]Policy - wg sync.WaitGroup + store Store + files Files + gateway Gateway + ctx context.Context + mu sync.Mutex + active map[string]string + overrides map[string]Policy + policySessionID string // Generations are process-local; do not reuse a previous process's requests. + wg sync.WaitGroup } type Options struct { @@ -31,7 +32,7 @@ type Options struct { } func New(opts Options) *Service { - return &Service{store: opts.Store, files: opts.Files, gateway: opts.Gateway, ctx: opts.Context, active: map[string]string{}, overrides: map[string]Policy{}} + return &Service{store: opts.Store, files: opts.Files, gateway: opts.Gateway, ctx: opts.Context, active: map[string]string{}, overrides: map[string]Policy{}, policySessionID: newID()} } // Recover never replays a mutation whose terminal response was lost. diff --git a/internal/mbn/trial.go b/internal/mbn/trial.go index 13cc9f1f..0b317966 100644 --- a/internal/mbn/trial.go +++ b/internal/mbn/trial.go @@ -66,6 +66,11 @@ func (s *Service) observe(session Session, op *Operation, result *TrialResult) e } registration, err := session.Registration(ctx) if err != nil { + // Only this candidate's observation deadline permits trying another + // profile. Cancellation, lost ownership and transport errors stay fatal. + if errors.Is(ctx.Err(), context.DeadlineExceeded) && errors.Is(err, context.DeadlineExceeded) && s.ctx.Err() == nil { + return errors.Join(errRegistrationGoal, err) + } return err } match := registration.Registered && (op.Request.TargetPLMN == "" || registration.PLMN == op.Request.TargetPLMN) diff --git a/web/src/components/DeviceConfigTab.vue b/web/src/components/DeviceConfigTab.vue index 7d3ee55f..45678aef 100644 --- a/web/src/components/DeviceConfigTab.vue +++ b/web/src/components/DeviceConfigTab.vue @@ -1,5 +1,5 @@ @@ -160,13 +170,28 @@ const isPCSCBackend = computed(() => configuredBackend.value === 'pcsc') .config-protocol-field strong { display: block; color: var(--ui-text); font-size: var(--ui-font-body-sm); } .config-protocol-field small { display: block; margin-top: 2px; color: var(--ui-text-muted); font-size: var(--ui-font-caption); } .config-notice { margin: 0; padding: 11px 22px; border-top: 1px solid var(--ui-border); border-bottom: 1px solid var(--ui-border); background: color-mix(in srgb, var(--ui-warning) 6%, var(--ui-surface)); color: var(--ui-text-muted); font-size: var(--ui-font-body-sm); } -.config-actions { min-height: 70px; padding: 14px 18px; display: flex; align-items: center; justify-content: space-between; gap: 10px; } +.mbn-settings { margin-top: 18px; border: 1px solid var(--ui-border); border-radius: var(--ui-radius-xl); overflow: hidden; background: var(--ui-surface-strong); } +.mbn-settings :deep(.el-collapse-item__header) { height: auto; min-height: 76px; padding: 18px 22px; line-height: 1.5; border: 0; background: var(--ui-surface-strong); color: var(--ui-text); } +.mbn-settings :deep(.el-collapse-item__header:hover) { background: var(--ui-surface-muted); } +.mbn-settings :deep(.el-collapse-item__header:focus-visible) { outline: 2px solid var(--ui-accent); outline-offset: -3px; } +.mbn-settings :deep(.el-collapse-item__title) { min-width: 0; flex: 1; } +.mbn-settings :deep(.el-collapse-item__wrap) { border: 0; background: var(--ui-surface-strong); } +.mbn-settings :deep(.el-collapse-item__content) { padding: 22px; border-top: 1px solid var(--ui-border); } +.mbn-entry { display: flex; flex: 1; align-items: center; gap: 12px; min-width: 0; text-align: left; } +.mbn-entry-copy { display: grid; flex: 1; gap: 4px; min-width: 0; } +.mbn-entry-copy strong { color: var(--ui-text); font-size: var(--ui-font-body); font-weight: 650; } +.mbn-entry-copy small { color: var(--ui-text-muted); font-size: var(--ui-font-body-sm); font-weight: 400; } +.mbn-entry-action { margin: 0 12px; color: var(--ui-text-muted); font-size: var(--ui-font-body-sm); font-weight: 400; } +.config-actions { min-height: 76px; padding: 16px 22px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-top: 1px solid var(--ui-border); } +.config-actions :deep(.el-button) { min-height: 44px; } +.config-actions :deep(.el-icon) { margin-right: 6px; } .config-primary-actions { display: flex; align-items: center; gap: 10px; } @media (max-width: 760px) { .config-columns { grid-template-columns: minmax(0, 1fr); } .config-columns > section { padding: 18px 16px; } .config-columns > section + section { border-top: 1px solid var(--ui-border); border-left: 0; } + .mbn-settings :deep(.el-collapse-item__header), .mbn-settings :deep(.el-collapse-item__content) { padding: 18px 16px; } } @media (max-width: 520px) { @@ -175,5 +200,6 @@ const isPCSCBackend = computed(() => configuredBackend.value === 'pcsc') .config-actions { align-items: stretch; flex-direction: column-reverse; } .config-actions :deep(.el-button) { width: 100%; min-height: 44px; margin-left: 0; } .config-primary-actions { width: 100%; flex-direction: column-reverse; } + .mbn-entry-action { display: none; } } diff --git a/web/src/components/MBNFileLibrary.vue b/web/src/components/MBNFileLibrary.vue index 8b91dcc5..edf23c21 100644 --- a/web/src/components/MBNFileLibrary.vue +++ b/web/src/components/MBNFileLibrary.vue @@ -1,15 +1,20 @@ diff --git a/web/src/components/MBNPanel.vue b/web/src/components/MBNPanel.vue index eddabea3..082d87f9 100644 --- a/web/src/components/MBNPanel.vue +++ b/web/src/components/MBNPanel.vue @@ -1,6 +1,7 @@