diff --git a/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg new file mode 100644 index 00000000000..6fb26260845 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.CacheAlias.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.CacheAlias.cfg — sabotage: the refresh write aliases the +\* store-cached record (in-place mutation of the cached HistoryItem), so the store's +\* delta compare drops apiConfigName and the stale pin survives on disk. +\* RefreshPersists must be the violated invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Valid <- ValidAliased +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg b/docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg new file mode 100644 index 00000000000..f1e447f2340 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.ChildRestore.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.ChildRestore.cfg — sabotage: the delegated-child origin is +\* ignored, so a child's restore is decided like a user restore and the child is +\* refreshed to the global active profile. ChildPinStable must be the violated +\* invariant (PR 2649 human review, restore-provider-profile.ts:66). +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Decide <- DecideIgnoresOrigin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg b/docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg new file mode 100644 index 00000000000..27a3c722f1a --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.NoQueue.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.NoQueue.cfg — sabotage: the decision runs outside the +\* provider-profile mutation queue, so a user switch can interleave between the +\* decision's snapshot and the write. RefreshNamesEffectiveActive must be the +\* violated invariant (PR 2649 human review, ClineProvider.ts:1620). +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Valid <- ValidUnqueued +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg new file mode 100644 index 00000000000..a08441c7266 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.Sabotage.cfg @@ -0,0 +1,7 @@ +\* Sabotage check. The stale-pin guard is removed. FollowActive must fail. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Decide <- DecideAlwaysPin +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg b/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg new file mode 100644 index 00000000000..9864e2d5a68 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.StalePin.cfg @@ -0,0 +1,10 @@ +\* RestoreProfileDecision.StalePin.cfg — sabotage: a full-copy write persists the +\* caller's history-copy pin even when no write landed, so a stale copy overwrites +\* the persisted record's newer pin. NoWritePreservesPin must be the violated +\* invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + PersistedPin <- PersistedPinFullCopy +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg new file mode 100644 index 00000000000..0890cd67eab --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.WriteAbort.cfg @@ -0,0 +1,9 @@ +\* RestoreProfileDecision.WriteAbort.cfg — sabotage: Proceed reads the write outcome, +\* so the restore aborts when the refresh pin write rejects (the un-caught await +\* before the Task constructor). WriteFailureRestores must be the violated invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" + Proceed <- ProceedAbort +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.cfg b/docs/architecture/tla/RestoreProfileDecision.cfg new file mode 100644 index 00000000000..f99b401589c --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.cfg @@ -0,0 +1,6 @@ +\* RestoreProfileDecision.cfg — the decision must satisfy every invariant. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + NoActive = "none" +INVARIANTS TypeOK FollowActive PinNamesEffect LegacyFallback RefreshPersists WriteFailureRestores NoWritePreservesPin ChildPinStable RefreshNamesEffectiveActive diff --git a/docs/architecture/tla/RestoreProfileDecision.tla b/docs/architecture/tla/RestoreProfileDecision.tla new file mode 100644 index 00000000000..2b50f70247c --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecision.tla @@ -0,0 +1,209 @@ +---- MODULE RestoreProfileDecision ---- +\* Models src/core/webview/restore-provider-profile.ts resolveRestoreProfileActivation. +\* Source: HistoryItem.apiConfigName (the pin) and the currentApiConfigName global, +\* resolved against the profile list by ClineProvider.createTaskWithHistoryItemUnlocked. +\* Sink: the decision record (reactivateProfileName, refreshedApiConfigName) consumed by +\* the same method: reactivate calls activateProviderProfile, refresh rewrites the pin +\* through the repinTaskProfilePin reducer (persisted to the task file) and hands the +\* record to the Task constructor. +\* Failure: restore re-activates a stale pinned profile, so the resumed task and the +\* task header keep the old provider's context window (issue #970). +\* Invariants (first version written before the fix): +\* FollowActive. With an existing pin and a resolvable active profile different from +\* it, a user restore must not reactivate the pinned profile. +\* PinNamesEffect. A refresh names exactly the active profile, and a reactivation +\* never also refreshes. +\* LegacyFallback. With no resolvable active profile, an existing pin is reactivated. +\* Added in the PR 2649 review ratchet (CodeRabbit round on d58eaba2c): +\* RefreshPersists. A refresh whose pin write succeeds leaves the persisted pin +\* naming the active profile. The caller must hand the store a record distinct from +\* the cached one (input rule in Valid); mutating the cached record in place makes +\* the store's delta compare drop apiConfigName, so the stale pin survives on disk +\* (CR thread on ClineProvider.ts:1651). +\* WriteFailureRestores. The restore reaches Task construction with the reachability +\* it would have had if the write had succeeded: Proceed must not read the write +\* outcome, because a failed refresh write is caught (CR thread on +\* ClineProvider.ts:1652). +\* Added in the PR 2649 human review round (edelauna, 2026-11-30): +\* ChildPinStable. A delegated child's restore never refreshes and reactivates only +\* the child's own task-local pin (thread on restore-provider-profile.ts:66; +\* delegation never changes the global profile, so the global active profile is not +\* the user's choice for the child). +\* RefreshNamesEffectiveActive. A refresh names the profile active at write time. +\* The input rule switchActive = active in Valid models the provider-profile +\* mutation queue: a user switch cannot interleave between the decision's snapshot +\* and the write (thread on ClineProvider.ts:1620; RestoreProfileDecision.NoQueue.cfg +\* sabotages the rule away). +\* NoWritePreservesPin. When no write lands, the persisted record keeps its own +\* current pin (input.savedPin), not the pin on the caller's possibly stale history +\* copy (input.pin) - the old-history-copy ownership (threads on ClineProvider.ts +\* :1657/1659; a full-copy write would revert newer fields). StalePin.cfg now +\* sabotages a full-copy write. +\* Proceed is inp.withinTimeout, no longer a constant: the queue timeout is the one +\* modeled stopper, so restored varies across reachable states and +\* WriteFailureRestores has content (thread on RestoreProfileDecision.tla:103). +\* Run each config on RestoreProfileDecisionMC.tla. The MC module holds the sabotage. +\* Expected: Spec.cfg passes every invariant; Sabotage.cfg fails FollowActive; +\* CacheAlias.cfg fails RefreshPersists; WriteAbort.cfg fails WriteFailureRestores; +\* StalePin.cfg fails NoWritePreservesPin; ChildRestore.cfg fails ChildPinStable; +\* NoQueue.cfg fails RefreshNamesEffectiveActive. +\* Result: Spec.cfg checks and holds all nine invariants; each sabotage cfg violates +\* the invariant it names (state counts in the check log, see the commit message). +\* Not modeled: the profile list (pinnedProfileExists is an oracle the caller computes), +\* the activateProviderProfile settings side effects, mode restoration, and the CLI +\* runtime skip flag (checked before the decision runs). The settings capture after the +\* activation is modeled only through the serialization rule in Valid. +\* Cost: TLC finishes in under 1 second per config. +\* Review (PR 2649, round on d58eaba2c): 1 covered (LegacyFallback - the missing-profile +\* proof case of the Regression Evidence check), 2 added (RefreshPersists + the +\* distinct-record input rule, CR thread ClineProvider.ts:1651; WriteFailureRestores, +\* CR thread ClineProvider.ts:1652), 1 gap (CR thread +\* ClineProvider.restore-follows-active-profile.spec.ts:123 - test-harness settings; +\* the model has no test doubles, the harness assertions pin it directly). +\* Review (PR 2649, round on bd9eb7d82): 1 covered (RefreshPersists + +\* WriteFailureRestores were already modeled; the defect was the passing cfg +\* checking only four of the six invariants - all six are checked now, CR thread +\* RestoreProfileDecision.cfg:6), 3 gap (mutation-diff survivors on bd9eb7d82: +\* the re-pin log text and the deleted-profile else-if guard are log/branch-level, +\* pinned by unit tests in ClineProvider.restore-follows-active-profile.spec.ts; +\* the defensive profile?.name chain is an equivalent mutant documented beside +\* the condition in ClineProvider.ts). +\* Review (PR 2649, round on 6ca11ea04): 1 gap (CR thread on +\* ClineProvider.restore-follows-active-profile.spec.ts:403 - the fall-through +\* restore must construct the task from the exact unresolved-settings snapshot; +\* expressing it would mean modeling the caller's profile.apiProvider activation +\* guard, which sits outside the decision record like the activation side +\* effects above; pinned by the strengthened exact-config unit assertion). +\* Review (PR 2649, round on ea2d69b75): 1 added (NoWritePreservesPin + the sink +\* fallback it pins: the no-write path now persists the selected input's pin, +\* factored as PersistedPin so StalePin.cfg sabotages the stale form; CR thread +\* RestoreProfileDecision.tla:109), 0 covered, 0 gap. +\* Review (PR 2649, human round 1, edelauna 2026-11-30): 3 added (ChildPinStable + +\* the origin input, thread restore-provider-profile.ts:66; RefreshNamesEffectiveActive +\* + the switchActive input and the queue rule in Valid, thread ClineProvider.ts:1620; +\* the savedPin input making NoWritePreservesPin pin the persisted record's own pin +\* instead of the caller's copy, threads ClineProvider.ts:1657/1659), 1 changed +\* (Proceed is inp.withinTimeout instead of TRUE so WriteFailureRestores is a real +\* constraint; WriteAbort.cfg still fails it, thread RestoreProfileDecision.tla:103), +\* 1 covered (FollowActive and LegacyFallback were already the stale-pin and +\* missing-profile behavior the round's other threads restate). + +CONSTANT NoActive \* sentinel: no resolvable active profile at restore time + +VARIABLES input, decision, storedPin, restored + +vars == <> + +NoProfile == "absent" \* decision marker: reactivate nothing +Keep == "keep" \* decision marker: preserve the stored pin + +Input == + [pin: {"p1", "p2", "absent"}, active: {"p1", "p2", NoActive}, + pinExists: BOOLEAN, pinWriteOk: BOOLEAN, distinctRecord: BOOLEAN, + origin: {"user", "child"}, savedPin: {"p1", "p2", "absent"}, + switchActive: {"p1", "p2", NoActive}, withinTimeout: BOOLEAN] + +\* Mirrors resolveRestoreProfileActivation rule for rule, origin included: a +\* delegated child's own task-local pin is authoritative and never refreshed. +Decide(inp) == + IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF inp.origin = "child" THEN + IF inp.pinExists THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> Keep] + ELSE IF ~inp.pinExists THEN + IF inp.active # NoActive THEN [r |-> NoProfile, f |-> inp.active] + ELSE [r |-> NoProfile, f |-> Keep] + ELSE IF inp.active = NoActive THEN [r |-> inp.pin, f |-> Keep] + ELSE IF inp.active = inp.pin THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> inp.active] + +\* A refresh-shaped input is one whose decision carries a new pin. +Refreshes(inp) == Decide(inp).f # Keep + +\* The sink: the pin persisted after one restore. A refresh whose write succeeds on +\* a record distinct from the store-cached one patches the pin on the store's current +\* record; every other path writes nothing, so the persisted record keeps its own +\* current pin - never the pin on the caller's possibly stale history copy. +PersistedPin(dec, inp, prev) == + IF dec.f # Keep /\ inp.pinWriteOk /\ inp.distinctRecord THEN dec.f ELSE inp.savedPin + +\* Caller rules: no existing flag for an absent pin; a refresh write is built from a +\* record distinct from the store-cached one (a copy), never the cached record; and +\* the mutation queue serializes the restore, so no user switch can interleave +\* between the decision's profile snapshot and the write. +Valid(inp) == + /\ ((inp.pin = "absent") => (~inp.pinExists)) + /\ (Refreshes(inp) => inp.distinctRecord) + /\ inp.switchActive = inp.active + +\* The queue timeout is the one modeled stopper: with runToCompletion a failed +\* refresh write is caught and the restore still reaches Task construction, while a +\* timeout rejects the caller before it. Not a constant, so restored varies. +Proceed(dec, inp) == inp.withinTimeout + +Init == + /\ input = [pin |-> "absent", active |-> NoActive, pinExists |-> FALSE, + pinWriteOk |-> TRUE, distinctRecord |-> TRUE, + origin |-> "user", savedPin |-> "absent", + switchActive |-> NoActive, withinTimeout |-> TRUE] + /\ decision = Decide(input) + /\ storedPin = input.savedPin + /\ restored = Proceed(Decide(input), input) + +Next == + \E inp \in Input : + /\ Valid(inp) + /\ input' = inp + /\ decision' = Decide(inp) + \* An aliased write (the cached record handed back to the store) makes the + \* delta compare omit apiConfigName, so the stale pin survives on disk. + /\ storedPin' = PersistedPin(decision', inp, storedPin) + /\ restored' = Proceed(decision', inp) + +Spec == Init /\ [][Next]_vars + +TypeOK == + /\ decision.r \in {"p1", "p2", "absent"} + /\ decision.f \in {"p1", "p2", "keep"} + /\ storedPin \in {"p1", "p2", "absent"} + /\ restored \in BOOLEAN + +FollowActive == + (input.pin # "absent" /\ input.origin = "user" /\ input.pinExists + /\ input.active # NoActive /\ input.active # input.pin) => decision.r = NoProfile + +PinNamesEffect == + /\ (decision.f # Keep) => decision.f = input.active + /\ (decision.r # NoProfile) => decision.f = Keep + +LegacyFallback == + (input.pin # "absent" /\ input.origin = "user" /\ input.pinExists + /\ input.active = NoActive) => decision.r = input.pin + +RefreshPersists == + (decision.f # Keep /\ input.pinWriteOk) => storedPin = decision.f + +\* No write landed (no refresh, a failed refresh write, or an aliased record the +\* store's delta compare drops): the persisted record keeps its own current pin, so +\* the caller's stale history copy cannot overwrite a newer one. +NoWritePreservesPin == + (~(decision.f # Keep /\ input.pinWriteOk /\ input.distinctRecord)) => storedPin = input.savedPin + +\* A delegated child is never refreshed to the global profile and reactivates only +\* its own task-local pin. +ChildPinStable == + (input.origin = "child") => + /\ decision.f = Keep + /\ (decision.r # NoProfile) => decision.r = input.pin + +\* The queue serialized the restore, so a refresh names the profile active at write +\* time - the same profile the decision snapshotted. +RefreshNamesEffectiveActive == + (decision.f # Keep) => decision.f = input.switchActive + +\* The restore reaches Task construction with the reachability it would have had if +\* the refresh write had succeeded: Proceed must not read the write outcome. +WriteFailureRestores == + restored = Proceed(decision, [input EXCEPT !.pinWriteOk = TRUE]) + +==== diff --git a/docs/architecture/tla/RestoreProfileDecisionMC.tla b/docs/architecture/tla/RestoreProfileDecisionMC.tla new file mode 100644 index 00000000000..c075724b4a4 --- /dev/null +++ b/docs/architecture/tla/RestoreProfileDecisionMC.tla @@ -0,0 +1,50 @@ +---- MODULE RestoreProfileDecisionMC ---- +\* Model-checking settings for RestoreProfileDecision. +EXTENDS RestoreProfileDecision + +\* Sabotage: the stale-pin guard is removed. The pin is always re-activated when it +\* exists (the pre-fix behavior) and the pin is never refreshed. FollowActive must fail. +DecideAlwaysPin(inp) == + IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF inp.pinExists THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> Keep] + +\* Sabotage: the delegated-child origin is ignored, so a child's restore is decided +\* like a user restore and the child is refreshed to the global active profile. +\* ChildPinStable must fail. The user rules are inlined (a cfg override of Decide +\* substitutes every occurrence, including inside this operator's own body). +DecideIgnoresOrigin(inp) == + IF inp.pin = "absent" THEN [r |-> NoProfile, f |-> Keep] + ELSE IF ~inp.pinExists THEN + IF inp.active # NoActive THEN [r |-> NoProfile, f |-> inp.active] + ELSE [r |-> NoProfile, f |-> Keep] + ELSE IF inp.active = NoActive THEN [r |-> inp.pin, f |-> Keep] + ELSE IF inp.active = inp.pin THEN [r |-> inp.pin, f |-> Keep] + ELSE [r |-> NoProfile, f |-> inp.active] + +\* Sabotage: the refresh write aliases the store-cached record (the restore mutates +\* the cached item in place before the write), so the store's delta compare +\* drops apiConfigName and the stale pin survives on disk. Only the distinct-record +\* rule is dropped, so RefreshPersists is the violated invariant. +ValidAliased(inp) == + /\ ((inp.pin = "absent") => (~inp.pinExists)) + /\ inp.switchActive = inp.active + +\* Sabotage: the decision runs outside the provider-profile mutation queue, so a user +\* switch can interleave between the decision's snapshot and the write. +\* RefreshNamesEffectiveActive must fail. +ValidUnqueued(inp) == + /\ ((inp.pin = "absent") => (~inp.pinExists)) + /\ (Refreshes(inp) => inp.distinctRecord) + +\* Sabotage: the restore aborts when the refresh write rejects (Proceed reads the +\* write outcome). WriteFailureRestores must fail. +ProceedAbort(dec, inp) == (dec.f = Keep) \/ inp.pinWriteOk + +\* Sabotage: a full-copy write persists the caller's history-copy pin even when no +\* write landed, so a stale copy overwrites the persisted record's newer pin. +\* NoWritePreservesPin must fail. +PersistedPinFullCopy(dec, inp, prev) == + IF dec.f # Keep /\ inp.pinWriteOk THEN dec.f ELSE inp.pin + +==== diff --git a/scripts/check-task-lifecycle.ts b/scripts/check-task-lifecycle.ts index bf05ad68e96..f3c6f565b4c 100644 --- a/scripts/check-task-lifecycle.ts +++ b/scripts/check-task-lifecycle.ts @@ -7,8 +7,11 @@ import { completeDelegatedChild, delegateTaskToChild, interruptDelegatedChild, + repinTaskProfilePin, + restoredProfileOriginOf, settleRejectedCreateSubtaskAction, } from "../src/core/task-persistence/taskLifecycle" +import { resolveRestoreProfileActivation } from "../src/core/webview/restore-provider-profile" const taskIds = ["parent", "child-a", "child-b"] as const type TaskId = (typeof taskIds)[number] @@ -20,6 +23,7 @@ interface Transition { delegation?: { parentId: TaskId } completion?: { childId: TaskId; pendingActionId?: string } settlement?: { taskId: TaskId; actionId: string } + restore?: { taskId: TaskId; activeProfileName: string | undefined; pinnedProfileExists: boolean } } interface TraceStep { @@ -36,7 +40,15 @@ interface WitnessContext { const MAX_DEPTH = 12 const MAX_STATES = 10_000 const actionIds = ["action-1", "action-2"] as const -const expectedActions = ["delegate", "interrupt", "complete", "abandon", "stage", "settle-rejected"] as const +const expectedActions = [ + "delegate", + "interrupt", + "complete", + "abandon", + "stage", + "settle-rejected", + "restore-repin", +] as const const semanticLandmarks = { "interrupted-child-redelegation": (state: ModelState) => state.parent?.status === "delegated" && @@ -99,6 +111,14 @@ const semanticWitnesses = { canonicalTask(after.pendingAction) === canonicalTask(beforeAction) ) }, + // A delegated child's restore keeps the child's task-local pin (never refreshed + // to the global active profile) while the restore transition still ran. + "child-restore-keeps-pin": ({ prev, next, transition }: WitnessContext) => { + if (transition.restore === undefined) return false + const before = prev[transition.restore.taskId] + const after = next[transition.restore.taskId] + return !!before?.parentTaskId && !!before.apiConfigName && after?.apiConfigName === before.apiConfigName + }, } satisfies Record boolean> function task(id: TaskId, parentTaskId?: TaskId): HistoryItem { @@ -114,6 +134,9 @@ function task(id: TaskId, parentTaskId?: TaskId): HistoryItem { parentTaskId, rootTaskId: parentTaskId ? "parent" : undefined, childIds: [], + // Every task carries the task-local pin a save persists; delegation assigns + // children their own task-local profile pin. + apiConfigName: "pin-a", } } @@ -221,6 +244,34 @@ function transitions(state: ModelState): Transition[] { }) } } + // Restore: the provider-profile decision for a task whose pin the history item + // carries. The environment inputs are the restore-time profile list state: the + // resolvable active profile and whether the pinned profile still exists. The + // decision is the production resolveRestoreProfileActivation; the persisted + // mutation goes through the production repinTaskProfilePin reducer. + const restoreInputs = [ + { activeProfileName: undefined, pinnedProfileExists: true }, + { activeProfileName: "pin-a", pinnedProfileExists: true }, + { activeProfileName: "pin-b", pinnedProfileExists: true }, + { activeProfileName: "pin-b", pinnedProfileExists: false }, + ] as const + for (const id of taskIds) { + const record = state[id] + if (!record?.apiConfigName) continue + for (const input of restoreInputs) { + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName: record.apiConfigName, + activeProfileName: input.activeProfileName, + pinnedProfileExists: input.pinnedProfileExists, + profileOrigin: restoredProfileOriginOf(record), + }) + result.push({ + name: `restore-repin(${id}, active=${String(input.activeProfileName)}, exists=${String(input.pinnedProfileExists)})`, + next: replace(state, repinTaskProfilePin(record, decision.refreshedApiConfigName)), + restore: { taskId: id, ...input }, + }) + } + } return result } @@ -292,7 +343,52 @@ function checkTransitionInvariants(previous: ModelState, transition: Transition) const before = previous[id] const after = transition.next[id] if (before?.status === "completed" && canonicalTask(before) !== canonicalTask(after)) { - violations.push(`${id}: completed task changed after ${transition.name}`) + // A restore may re-pin a completed record (reopening a finished task from + // history), but only through the patch-only reducer: apiConfigName is the + // only field a restore-repin may change on a completed task. + const repinOnly = + transition.restore?.taskId === id && + canonicalTask({ ...before, apiConfigName: after?.apiConfigName }) === canonicalTask(after) + if (!repinOnly) { + violations.push(`${id}: completed task changed after ${transition.name}`) + } + } + } + + const restore = transition.restore + if (restore) { + const before = previous[restore.taskId] + const after = transition.next[restore.taskId] + if (!before || !after) { + violations.push(`${restore.taskId}: restore-repin touched a missing record`) + } else { + const origin = restoredProfileOriginOf(before) + // ChildPinStable: a delegated child's restore never re-pins the child to + // the global active profile; the task-local pin survives every restore. + if (origin === "delegated-child" && after.apiConfigName !== before.apiConfigName) { + violations.push(`${restore.taskId}: delegated child's pin was refreshed to the global active profile`) + } + // UserPinFollowsActive: a user restore keeps the pin or re-pins it to the + // active profile exactly. + if ( + origin === "user" && + after.apiConfigName !== before.apiConfigName && + after.apiConfigName !== restore.activeProfileName + ) { + violations.push(`${restore.taskId}: restore re-pinned to a profile that is not the active one`) + } + // RepinPatchesOnlyPin: the persisted mutation changes only apiConfigName, + // so a stale caller copy cannot revert newer token counts or timestamps. + const repinned = { ...before, apiConfigName: after.apiConfigName } + if (canonicalTask(repinned) !== canonicalTask(after)) { + violations.push(`${restore.taskId}: restore-repin changed fields other than apiConfigName`) + } + for (const otherId of taskIds) { + if (otherId === restore.taskId) continue + if (canonicalTask(previous[otherId]) !== canonicalTask(transition.next[otherId])) { + violations.push(`${otherId}: restore-repin of ${restore.taskId} changed an unrelated record`) + } + } } } diff --git a/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts new file mode 100644 index 00000000000..d6de86cb138 --- /dev/null +++ b/src/__tests__/ClineProvider.restore-follows-active-profile.spec.ts @@ -0,0 +1,802 @@ +// npx vitest run __tests__/ClineProvider.restore-follows-active-profile.spec.ts +// +// Issue #970: the task header's context window stays on the old provider after a +// stop -> switch provider -> restore flow, and the usage bar can exceed 100%. +// Root cause on this path: ClineProvider.createTaskWithHistoryItemUnlocked +// re-activates the profile pinned in HistoryItem.apiConfigName even when the user +// has switched to a different profile while the task was stopped, so the restored +// task and the header keep the old provider's context window. +// +// Failure sentences these tests prevent: +// 1. Restoring a task re-activates a stale pinned profile that differs from the +// user's active profile, so the resumed task keeps the old provider's limits. +// 2. The history item keeps pinning a profile that is not in effect for the +// restored task, so every later restore flips the configuration back. +// 3. A restore whose pinned profile no longer exists loses the re-pin to the +// profile that is actually in effect. +// 4. The restored task is built with settings that do not follow the profile in +// effect after activation (a stale provider/model would keep the old context +// window even with a correct pin). +// 5. A restore whose currentApiConfigName does not resolve in the profile list +// loses the legacy reactivation of the still-existing pinned profile. +// 6. A failed pin write aborts the restore after the previous task was already +// evicted, so the task cannot be resumed at all. +// 7. The re-pinned record mutates the store-owned cached item, so the store's +// delta compare drops apiConfigName and the stale pin survives on disk. +// 8. A restore whose pinned profile exists but carries no configured provider +// settings logs the deleted-profile warning, so the log misreports the state. +// 9. A delegated child is restored onto the global active profile and its saved +// task-local pin is overwritten with it (PR 2649 human review, +// restore-provider-profile.ts:66; delegation never changes the global profile). +// 10. A restore whose pinned profile failed schema validation on load (so +// listConfig drops it) overwrites the pin as if the profile were deleted +// (PR 2649 human review, restore-provider-profile.ts:57). +// 11. A user profile switch interleaves between the restore's profile snapshot, +// its decision and the settings capture, so the task is pinned to one profile +// name and built from another profile's settings (PR 2649 human review, +// ClineProvider.ts:1620; the decision now runs in the provider-profile +// mutation queue). +// 12. The re-pin write serializes the caller's stale full copy, so newer token +// counts or timestamps are reverted, or the live rootTask/parentTask +// references attached by the cancel-rehydrate path fail the write with +// "Converting circular structure to JSON" (PR 2649 human review, +// ClineProvider.ts:1657/1659; the re-pin patches only apiConfigName on the +// current store record). +// 13. During a rehydrate of the current task, the old task's final save runs +// after the re-pin and restores the old profile name (PR 2649 human review, +// ClineProvider.ts:1670; the old task's pin is synced before its abort). +// +// Red-verify: tests 1 and 3 fail on pre-fix code because the restore block +// activates the stale pin unconditionally. Test 6 fails because the rejected +// updateTaskHistory await escapes before the Task is constructed. Test 7 fails +// because the mutated cache makes the store persist the old pin. Test 8's +// exact-settings assertion fails when the caller's profile.apiProvider guard +// is dropped (activation then reports 'model-of-provider-1') or when the +// fall-through skips Task construction; a bare resolves-defined check passed +// both (review round on 6ca11ea04). Test 9 fails on the pre-review code because +// the stale child pin is refreshed to the global profile. Test 10 fails because +// the pin is overwritten through the deleted-profile branch. Test 11 fails +// without the queue because the switch interleaves before the settings capture. +// Test 12 fails because the full-copy write regresses the tokens and rejects on +// the circular lineage. Test 13 fails because the old task's pin is never synced. + +import { describe, it, expect, vi, beforeEach } from "vitest" +import { mkdtemp, readFile, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { providerIdentifiers } from "@roo-code/types" +import type { HistoryItem } from "@roo-code/types" + +/* vscode mock for Task/Provider imports */ +vi.mock("vscode", () => { + const window = { + createTextEditorDecorationType: vi.fn(() => ({ dispose: vi.fn() })), + showErrorMessage: vi.fn(), + onDidChangeActiveTextEditor: vi.fn(() => ({ dispose: vi.fn() })), + } + const workspace = { + getConfiguration: vi.fn(() => ({ + get: vi.fn((_key: string, defaultValue: unknown) => defaultValue), + update: vi.fn(), + })), + workspaceFolders: [], + } + const env = { machineId: "test-machine", uriScheme: "vscode", appName: "VSCode", language: "en", sessionId: "sess" } + const Uri = { file: (p: string) => ({ fsPath: p, toString: () => p }) } + const commands = { executeCommand: vi.fn() } + const ExtensionMode = { Development: 2 } + const version = "1.0.0-test" + return { window, workspace, env, Uri, commands, ExtensionMode, version } +}) + +vi.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + captureTaskCompleted: vi.fn(), + }, + }, +})) + +vi.mock("../core/task-persistence/taskMessages", () => ({ + readTaskMessages: vi.fn().mockResolvedValue([]), +})) + +vi.mock("../core/task-persistence", async (importOriginal) => { + const real = await importOriginal() + return { + ...real, + readApiMessages: vi.fn().mockResolvedValue([]), + saveApiMessages: vi.fn(async ({ messages }: { messages: unknown[] }) => messages), + saveTaskMessages: vi.fn(async ({ messages }: { messages: unknown[] }) => messages), + } +}) + +// The tail of createTaskWithHistoryItemUnlocked constructs a real Task. Replace it +// with a recording double so the test can observe the history item and the API +// configuration the restored task is built from without booting the whole task +// runtime. +vi.mock("../core/task/Task", async (importOriginal) => { + const real = await importOriginal() + // A regular (non-arrow) function so `new Task(...)` constructs the double. + const TaskDouble = vi.fn(function TaskDoubleMock(this: Record, _options: unknown) { + this.taskId = "restored-task" + this.instanceId = "instance-1" + this.parentTask = undefined + this.abortTask = vi.fn(async () => {}) + this.emit = vi.fn() + this.clineMessages = [] + this.apiConversationHistory = [] + }) + return { ...real, Task: TaskDouble } +}) + +import { ClineProvider } from "../core/webview/ClineProvider" +import { Task } from "../core/task/Task" +import { TaskHistoryStore } from "../core/task-persistence/TaskHistoryStore" +import type { ProviderSettingsEntry } from "@roo-code/types" +import { makeProviderStub } from "./helpers/provider-stub" + +function makeHistoryItem(apiConfigName: string, extra: Partial = {}): HistoryItem { + return { + id: "task-1", + number: 1, + ts: 1700000000000, + task: "summarize the repository", + tokensIn: 100, + tokensOut: 20, + totalCost: 0.01, + apiConfigName, + ...extra, + } satisfies HistoryItem +} + +type ProfileEntry = { name: string; apiProvider?: string } + +interface RestoreHarnessOptions { + profiles: ProfileEntry[] + /** Value reported for the currentApiConfigName global (may be absent from `profiles`). */ + activeProfileName: string | undefined + /** Whether the pinned profile exists in the raw settings file despite missing from `profiles`. */ + pinnedProfileOnDisk?: boolean + /** Reject the atomic re-pin write once with this error. */ + failRepinWith?: Error + /** Real store to read history through and to persist with the real write path. */ + taskHistoryStore?: TaskHistoryStore + /** Tasks pre-seeded into the provider's real TaskRegistry (stack order). */ + tasks?: Task[] + /** Hook fired when the restore reads the profile list, while it is in flight. */ + onListConfig?: () => void +} + +function makeRestoreHarness(options: RestoreHarnessOptions) { + const timeline: string[] = [] + const listConfig = vi.fn(async () => { + timeline.push("listConfig") + options.onListConfig?.() + return options.profiles + }) + const hasRawConfigName = vi.fn(async () => options.pinnedProfileOnDisk ?? false) + const getGlobalState = vi.fn((key: string) => + key === "currentApiConfigName" ? options.activeProfileName : undefined, + ) + // Activation switches the settings getState observes, mirroring the real + // contract: after activateProviderProfile, getState reports the activated + // profile's provider and model. The restore runs the unlocked variant inside + // the provider-profile mutation queue, so the double replaces that method. + let effectiveProfile = options.activeProfileName + const activateProviderProfileUnlocked = vi.fn(async ({ name }: { name: string }) => { + timeline.push(`activate:${name}`) + effectiveProfile = name + }) + const log = vi.fn() + const updateTaskHistoryMock = vi.fn(async () => []) + // In-memory record store for the atomic re-pin patch. The updater receives the + // current record and its result becomes the stored record, mirroring the real + // store's read-update-write under one lock. + const records = new Map() + const atomicReadAndUpdate = vi.fn( + async (taskId: string, updater: (current: HistoryItem) => HistoryItem): Promise => { + timeline.push("repin") + if (options.failRepinWith) { + throw options.failRepinWith + } + const current = records.get(taskId) + if (!current) { + throw new Error(`[TaskHistoryStore] atomicReadAndUpdate: task ${taskId} not found in cache`) + } + const updated = updater(current) + records.set(taskId, updated) + return [updated] + }, + ) + const getState = vi.fn(async () => { + timeline.push("getState") + const settings = options.profiles.find((profile) => profile.name === effectiveProfile) + return { + apiConfiguration: { + apiProvider: settings?.apiProvider ?? providerIdentifiers.openrouter, + apiModelId: settings ? `model-of-${settings.name}` : "model-of-unresolved", + }, + enableCheckpoints: false, + checkpointTimeout: 10, + experiments: {}, + diffFuzzyThreshold: 0.8, + } + }) + + const provider = makeProviderStub({ + contextProxy: { globalStorageUri: { fsPath: "/tmp" } }, + tasks: options.tasks, + }) + + Object.assign(provider, { + getState, + log, + updateGlobalState: vi.fn(async () => {}), + getGlobalState, + ["activateProviderProfileUnlocked"]: activateProviderProfileUnlocked, + // The real queue machinery, bound to the stub so the restore's serialization + // semantics (and the concurrent-switch ordering) are exercised for real. + enqueueProviderProfileMutation: ClineProvider.prototype["enqueueProviderProfileMutation"], + withProviderProfileMutationTimeout: ClineProvider.prototype["withProviderProfileMutationTimeout"], + activateProviderProfile: ClineProvider.prototype["activateProviderProfile"], + repinTaskProfile: ClineProvider.prototype["repinTaskProfile"], + updateTaskHistory: options.taskHistoryStore ? ClineProvider.prototype.updateTaskHistory : updateTaskHistoryMock, + taskHistoryStore: options.taskHistoryStore ?? { + get: () => undefined, + invalidate: async () => {}, + atomicReadAndUpdate, + }, + providerSettingsManager: { listConfig, hasRawConfigName }, + providerProfileMutationQueue: Promise.resolve(), + isViewLaunched: false, + postMessageToWebview: vi.fn(async () => {}), + addClineToStack: vi.fn(async () => {}), + getPendingEditOperation: vi.fn(() => undefined), + taskCreationCallback: vi.fn(), + getCurrentTask: vi.fn(() => undefined), + evictCurrentTask: vi.fn(async () => {}), + }) + + // Bracket notation for the private method, as the typed-test rules in + // AGENTS.md ask; element access keeps the real signature without a cast. + const createTaskWithHistoryItemUnlocked = ClineProvider.prototype["createTaskWithHistoryItemUnlocked"] + + const runRestore = (historyItem: HistoryItem) => + createTaskWithHistoryItemUnlocked.call(provider, historyItem, { startTask: false }) + + return { + runRestore, + provider, + activateProviderProfileUnlocked, + updateTaskHistory: updateTaskHistoryMock, + repin: atomicReadAndUpdate, + records, + hasRawConfigName, + listConfig, + getGlobalState, + log, + timeline, + } +} + +function constructedTaskConfig(): + { historyItem?: HistoryItem; apiConfiguration?: Record } | undefined { + const firstCall = vi.mocked(Task).mock.calls[0]?.[0] as + { historyItem?: HistoryItem; apiConfiguration?: Record } | undefined + return firstCall +} + +function constructedHistoryItem(): HistoryItem | undefined { + return constructedTaskConfig()?.historyItem +} + +describe("ClineProvider restore follows the active profile", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("keeps the active profile when it differs from the stale pin and re-pins the task to it", async () => { + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + }) + harness.records.set("task-1", makeHistoryItem("provider-1")) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + // The re-pin patches only apiConfigName on the current store record. + expect(harness.repin).toHaveBeenCalledWith("task-1", expect.any(Function)) + expect(harness.records.get("task-1")?.apiConfigName).toBe("provider-2") + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + // The re-pin decision must be visible in the log with both names: the + // active profile that stays in effect and the stale pin it replaces. + expect(harness.log).toHaveBeenCalledWith( + "Restoring task task-1 with active profile 'provider-2' instead of stale pinned profile 'provider-1'.", + ) + // The restored task must run on the active profile's settings, not the stale + // pin's provider/model. + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-provider-2", + }) + }) + + it("re-activates the pinned profile when it is still the active one", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: "provider-1", + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), + ) + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + // After the re-activation the restored task must run on the activated + // profile's provider and model. + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-of-provider-1", + }) + }) + + it("re-pins to the active profile when the pinned profile no longer exists", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + }) + harness.records.set("task-1", makeHistoryItem("deleted-profile")) + + await harness.runRestore(makeHistoryItem("deleted-profile")) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.repin).toHaveBeenCalledWith("task-1", expect.any(Function)) + expect(harness.records.get("task-1")?.apiConfigName).toBe("provider-2") + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-provider-2", + }) + }) + + it("re-activates the pin when no resolvable active profile exists", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: undefined, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), + ) + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + // The activation must be what the observed settings follow: with no active + // profile at restore time only the re-activated pin can supply provider/model. + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-of-provider-1", + }) + }) + + it("re-activates the existing pinned profile when currentApiConfigName is absent from the profile list", async () => { + // Regression-evidence case: the active name is a dangling pointer, the pin + // still exists. Legacy fallback re-activates the pin and must not write. + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: "ghost-profile", + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), + ) + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.anthropic, + apiModelId: "model-of-provider-1", + }) + }) + + it("continues the restore when the re-pin write rejects", async () => { + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + failRepinWith: new Error("simulated pin-write failure"), + }) + + // The previous task is already evicted at this point; the restore must not + // fail, and the task must still be constructed with the refreshed pin and + // the active configuration. + await expect(harness.runRestore(makeHistoryItem("provider-1"))).resolves.toBeDefined() + + expect(vi.mocked(Task).mock.calls.length).toBe(1) + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-provider-2", + }) + expect(harness.log).toHaveBeenCalledWith( + expect.stringContaining("Failed to persist re-pinned profile 'provider-2'"), + ) + }) + + it("persists the refreshed pin through the real TaskHistoryStore", async () => { + // Persistence-integrity case: the restore must re-pin the STORE-OWNED record + // without mutating the cached item in place (an in-place mutation would make + // the store's delta compare drop apiConfigName, leaving the stale pin on + // disk). The disk file is the oracle. + const storageRoot = await mkdtemp(join(tmpdir(), "zoo-970-store-")) + try { + const store = new TaskHistoryStore(storageRoot) + await store.upsert(makeHistoryItem("provider-1")) + // Route the store-cached object through the restore, exactly as the + // history-navigation callers do. + const cached = store.get("task-1") + expect(cached?.apiConfigName).toBe("provider-1") + + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + taskHistoryStore: store, + }) + + await harness.runRestore(cached as HistoryItem) + + const disk = JSON.parse( + await readFile(join(storageRoot, "tasks", "task-1", "history_item.json"), "utf8"), + ) as HistoryItem + expect(disk.apiConfigName).toBe("provider-2") + // The cache is updated by the store's own write path, not by the restore. + expect(store.get("task-1")?.apiConfigName).toBe("provider-2") + } finally { + await rm(storageRoot, { recursive: true, force: true }) + } + }) + + it("does not warn about a deleted profile when the pinned profile exists without a configured provider", async () => { + // The pinned profile exists but carries no apiProvider settings: the + // reactivation branch skips activation, and the restore must fall through + // without the deleted-profile warning. That warning is reserved for a pin + // whose profile is absent from the list. + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1" }], + activeProfileName: undefined, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + // The fall-through must still construct the task from the settings snapshot + // getState reports after no activation ran: the unresolved-profile fallback. + // A wrongly re-activated settings-less pin surfaces 'model-of-provider-1' + // here, and a restore that skips Task construction leaves no call to read. + expect(vi.mocked(Task).mock.calls.length).toBe(1) + expect(constructedTaskConfig()?.apiConfiguration).toStrictEqual({ + apiProvider: providerIdentifiers.openrouter, + apiModelId: "model-of-unresolved", + }) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() + expect(harness.log).not.toHaveBeenCalledWith(expect.stringContaining("no longer exists")) + }) + + it("keeps a delegated child on its own task-local profile and never re-pins it to the global profile", async () => { + // Delegation assigns the child its own profile (selectHandoffExecutionContext) + // and never changes the global profile, so the global active profile is not + // the user's choice for this child: the child's own pin is reactivated and + // never overwritten with the global profile. + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + }) + + await harness.runRestore(makeHistoryItem("provider-1", { parentTaskId: "parent-1", rootTaskId: "root-1" })) + + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-1" }, + expect.objectContaining({ persistTaskHistory: false }), + expect.any(AbortSignal), + ) + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + expect(harness.log).not.toHaveBeenCalledWith(expect.stringContaining("stale pinned profile")) + }) + + it("keeps the configuration when a delegated child's pin no longer exists instead of re-pinning to the global profile", async () => { + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + }) + + await harness.runRestore(makeHistoryItem("deleted-profile", { parentTaskId: "parent-1" })) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.repin).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("deleted-profile") + expect(harness.log).toHaveBeenCalledWith(expect.stringContaining("no longer exists")) + }) + + it("keeps the saved pin when the pinned profile exists on disk but fails validation on load", async () => { + // listConfig drops a profile that fails schema validation, which makes a + // recoverable profile look deleted. The restore must keep the saved name and + // warn instead of overwriting the pin (PR 2649 human review, + // restore-provider-profile.ts:57). + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + pinnedProfileOnDisk: true, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.repin).not.toHaveBeenCalled() + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-1") + expect(harness.log).toHaveBeenCalledWith(expect.stringContaining("exists but failed to load")) + }) + + it("re-pins to the active profile when the pinned profile is genuinely absent from disk", async () => { + // Companion to the validation-failure case: without the on-disk entry the + // deleted-profile re-pin still applies, so the issue #970 contract holds. + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-2", apiProvider: providerIdentifiers.openrouter }], + activeProfileName: "provider-2", + pinnedProfileOnDisk: false, + }) + harness.records.set("task-1", makeHistoryItem("deleted-profile")) + + await harness.runRestore(makeHistoryItem("deleted-profile")) + + expect(harness.hasRawConfigName).toHaveBeenCalledWith("deleted-profile") + expect(harness.repin).toHaveBeenCalledWith("task-1", expect.any(Function)) + expect(harness.records.get("task-1")?.apiConfigName).toBe("provider-2") + }) + + it("serializes the decision, activation and settings capture against a concurrent profile switch", async () => { + // The whole read -> decide -> activate -> settings-capture sequence runs + // inside the provider-profile mutation queue: a user switch enqueued before + // the restore finishes must run only after the restore captured its settings, + // so the task cannot be pinned to one profile and built from another's + // settings (PR 2649 human review, ClineProvider.ts:1620). + const harness = makeRestoreHarness({ + profiles: [{ name: "provider-1", apiProvider: providerIdentifiers.anthropic }], + activeProfileName: "provider-1", + // The user switch arrives while the restore is in flight (right after its + // profile snapshot): the real public method enqueues on the same + // provider-profile mutation queue, so it can only run after the restore's + // queue entry completes, which is after getState captured the settings. + onListConfig: () => { + void harness.provider.activateProviderProfile({ name: "provider-1" }) + }, + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(harness.timeline).toStrictEqual(["listConfig", "activate:provider-1", "getState", "activate:provider-1"]) + }) + + it("patches only apiConfigName so a newer token count survives the re-pin", async () => { + // The caller's snapshot is stale: a concurrent save advanced the stored token + // counts after the restore read its copy. The atomic patch must keep the + // newer counts and change only the pin (PR 2649 human review, + // ClineProvider.ts:1659). + const storageRoot = await mkdtemp(join(tmpdir(), "zoo-970-repin-")) + try { + const store = new TaskHistoryStore(storageRoot) + await store.upsert(makeHistoryItem("provider-1")) + const staleSnapshot = store.get("task-1") + // The concurrent save: newer token counts land after the snapshot was read. + await store.upsert(makeHistoryItem("provider-1", { tokensIn: 500, tokensOut: 90 })) + + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + taskHistoryStore: store, + }) + + await harness.runRestore(staleSnapshot as HistoryItem) + + const disk = JSON.parse( + await readFile(join(storageRoot, "tasks", "task-1", "history_item.json"), "utf8"), + ) as HistoryItem + expect(disk.apiConfigName).toBe("provider-2") + expect(disk.tokensIn).toBe(500) + expect(disk.tokensOut).toBe(90) + } finally { + await rm(storageRoot, { recursive: true, force: true }) + } + }) + + it("persists the re-pin even when the cancel-rehydrate copy carries circular task lineage", async () => { + // cancelTaskInternal rehydrates with the LIVE rootTask/parentTask attached to + // the history item ({ ...historyItem, rootTask, parentTask }). A full-copy + // write of that record rejects with "Converting circular structure to JSON", + // so the re-pin silently failed for subtasks. The atomic patch writes the + // store's own record and must not touch the live references (PR 2649 human + // review, ClineProvider.ts:1657). + const storageRoot = await mkdtemp(join(tmpdir(), "zoo-970-cycle-")) + try { + const store = new TaskHistoryStore(storageRoot) + await store.upsert(makeHistoryItem("provider-1")) + const cached = store.get("task-1") + + const rootTask: Record = { taskId: "root-1" } + const parentTask: Record = { taskId: "parent-1" } + // The live Task objects reference each other and themselves. + rootTask["parent"] = parentTask + parentTask["root"] = rootTask + rootTask["self"] = rootTask + const enriched = { ...cached, rootTask, parentTask } as HistoryItem & { + rootTask: unknown + parentTask: unknown + } + + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + taskHistoryStore: store, + }) + + await harness.runRestore(enriched) + + const disk = JSON.parse( + await readFile(join(storageRoot, "tasks", "task-1", "history_item.json"), "utf8"), + ) as HistoryItem + expect(disk.apiConfigName).toBe("provider-2") + // The constructed task still receives the live lineage. + expect(constructedHistoryItem()?.apiConfigName).toBe("provider-2") + } finally { + await rm(storageRoot, { recursive: true, force: true }) + } + }) + + it("syncs the refreshed pin into the old task before its final save during a rehydrate", async () => { + // During a restore of the current task the old task is stopped after the + // re-pin write; its final save carries its own pin and would put the old + // profile name back. The old task's pin must be synced to the refreshed pin + // before the abort (PR 2649 human review, ClineProvider.ts:1670). + const oldTask = { + taskId: "task-1", + instanceId: "old-instance", + setTaskApiConfigName: vi.fn(), + abortTask: vi.fn(async () => {}), + emit: vi.fn(), + clineMessages: [], + apiConversationHistory: [], + } + const harness = makeRestoreHarness({ + profiles: [ + { name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ], + activeProfileName: "provider-2", + // Seed the real TaskRegistry with the old task so the rehydrate branch's + // in-place replace runs; the double provides only the members the + // rehydrate path touches (taskId, instanceId, abortTask, emit, + // setTaskApiConfigName, message arrays). + tasks: [oldTask as unknown as Task], + }) + harness.records.set("task-1", makeHistoryItem("provider-1")) + Object.assign(harness.provider, { + getCurrentTask: vi.fn(() => oldTask), + taskEventListeners: new WeakMap(), + performPreparationTasks: vi.fn(async () => {}), + }) + + await harness.runRestore(makeHistoryItem("provider-1")) + + expect(oldTask.setTaskApiConfigName).toHaveBeenCalledWith("provider-2") + // The sync must land before the abort, whose save would otherwise run last. + expect(oldTask.setTaskApiConfigName.mock.invocationCallOrder[0]).toBeLessThan( + oldTask.abortTask.mock.invocationCallOrder[0], + ) + }) +}) + +describe("ClineProvider deleteProviderProfile loads the fallback profile's settings", () => { + // Failure sentences these tests prevent: + // 1. Deleting the active profile changes the active name but not the settings, + // so a later task restore pins the new name and runs the deleted profile's + // settings (PR 2649 human review, ClineProvider.ts:1617). + // 2. Deleting a profile that is not active re-loads settings for no reason. + function makeDeleteHarness(currentApiConfigName: string | undefined) { + const setValues = vi.fn(async () => {}) + const log = vi.fn() + const activateProviderProfileUnlocked = vi.fn(async () => {}) + const provider = makeProviderStub({ + log, + contextProxy: { + globalStorageUri: { fsPath: "/tmp" }, + getValues: vi.fn(() => ({ currentApiConfigName })), + setValues, + }, + }) + Object.assign(provider, { + getProviderProfileEntries: vi.fn(() => [ + { id: "entry-1", name: "provider-1", apiProvider: providerIdentifiers.anthropic }, + { id: "entry-2", name: "provider-2", apiProvider: providerIdentifiers.openrouter }, + ]), + updateGlobalState: vi.fn(async () => {}), + activateProviderProfileUnlocked, + activateProviderProfile: ClineProvider.prototype["activateProviderProfile"], + enqueueProviderProfileMutation: ClineProvider.prototype["enqueueProviderProfileMutation"], + withProviderProfileMutationTimeout: ClineProvider.prototype["withProviderProfileMutationTimeout"], + providerProfileMutationQueue: Promise.resolve(), + postStateToWebview: vi.fn(async () => {}), + }) + const deleteProviderProfile = ClineProvider.prototype["deleteProviderProfile"] + return { + setValues, + activateProviderProfileUnlocked, + log, + run: (entry: ProviderSettingsEntry) => deleteProviderProfile.call(provider, entry), + } + } + + it("activates the fallback profile when the deleted profile was active", async () => { + const harness = makeDeleteHarness("provider-1") + + await harness.run({ id: "entry-1", name: "provider-1" }) + + // The stored active name and the loaded settings must move together: the + // fallback activation runs after the store write. + expect(harness.activateProviderProfileUnlocked).toHaveBeenCalledWith( + { name: "provider-2" }, + undefined, + expect.any(AbortSignal), + ) + expect(harness.setValues.mock.invocationCallOrder[0]).toBeLessThan( + harness.activateProviderProfileUnlocked.mock.invocationCallOrder[0], + ) + }) + + it("does not activate anything when the deleted profile was not active", async () => { + const harness = makeDeleteHarness("provider-2") + + await harness.run({ id: "entry-1", name: "provider-1" }) + + expect(harness.activateProviderProfileUnlocked).not.toHaveBeenCalled() + expect(harness.setValues).toHaveBeenCalledWith(expect.objectContaining({ currentApiConfigName: "provider-2" })) + }) + + it("keeps the deletion when the fallback activation rejects", async () => { + const harness = makeDeleteHarness("provider-1") + harness.activateProviderProfileUnlocked.mockRejectedValueOnce(new Error("activation failed")) + + await expect(harness.run({ id: "entry-1", name: "provider-1" })).resolves.toBeUndefined() + + expect(harness.log).toHaveBeenCalledWith(expect.stringContaining("Failed to activate profile 'provider-2'")) + }) +}) diff --git a/src/core/config/ProviderSettingsManager.ts b/src/core/config/ProviderSettingsManager.ts index 79a9d67c794..068460e6add 100644 --- a/src/core/config/ProviderSettingsManager.ts +++ b/src/core/config/ProviderSettingsManager.ts @@ -414,6 +414,27 @@ export class ProviderSettingsManager { } } + /** + * True when a config with this name exists in the raw settings file, including + * entries that schema validation drops from listConfig on load. + */ + public async hasRawConfigName(name: string): Promise { + try { + return await this.lock(async () => { + const content = await this.context.secrets.get(this.secretsKey) + if (!content) { + return false + } + const parsed = JSON.parse(content) as { apiConfigs?: Record } + return !!parsed.apiConfigs && Object.prototype.hasOwnProperty.call(parsed.apiConfigs, name) + }) + } catch { + // An unreadable or unparsable file resolves nothing; the caller keeps the + // saved pin rather than treating the profile as recoverable. + return false + } + } + /** * Save a config with the given name. * Preserves the ID from the input 'config' object if it exists, diff --git a/src/core/task-persistence/__tests__/taskLifecycle.spec.ts b/src/core/task-persistence/__tests__/taskLifecycle.spec.ts index 5d3129e0237..e15d61b8f2d 100644 --- a/src/core/task-persistence/__tests__/taskLifecycle.spec.ts +++ b/src/core/task-persistence/__tests__/taskLifecycle.spec.ts @@ -6,6 +6,8 @@ import { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + repinTaskProfilePin, + restoredProfileOriginOf, settleRejectedCreateSubtaskAction, } from "../taskLifecycle" @@ -185,3 +187,31 @@ describe("settleRejectedCreateSubtaskAction", () => { ) }) }) + +describe("restored task profile pin", () => { + it("derives the delegation ownership origin from the record lineage", () => { + expect(restoredProfileOriginOf(item("root"))).toBe("user") + expect(restoredProfileOriginOf(item("child", { parentTaskId: "root" }))).toBe("delegated-child") + }) + + it("patches only apiConfigName and returns a fresh record", () => { + const record = item("task-1", { + tokensIn: 500, + tokensOut: 90, + ts: 1700000000000, + apiConfigName: "provider-1", + }) + + const repinned = repinTaskProfilePin(record, "provider-2") + + expect(repinned).not.toBe(record) + expect(repinned).toStrictEqual({ ...record, apiConfigName: "provider-2" }) + }) + + it("keeps the record unchanged when a decision carries no refresh", () => { + const record = item("task-1", { apiConfigName: "provider-1" }) + + expect(repinTaskProfilePin(record, undefined)).toBe(record) + expect(repinTaskProfilePin(record, "")).toBe(record) + }) +}) diff --git a/src/core/task-persistence/index.ts b/src/core/task-persistence/index.ts index 0baf9ce57e6..86d87738055 100644 --- a/src/core/task-persistence/index.ts +++ b/src/core/task-persistence/index.ts @@ -21,7 +21,10 @@ export { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + repinTaskProfilePin, + restoredProfileOriginOf, settleRejectedCreateSubtaskAction, type HistoryItemStatus, + type RestoreProfileOrigin, VALID_TASK_STATUS_TRANSITIONS, } from "./taskLifecycle" diff --git a/src/core/task-persistence/taskLifecycle.ts b/src/core/task-persistence/taskLifecycle.ts index b8a5e571f03..ffabb39694f 100644 --- a/src/core/task-persistence/taskLifecycle.ts +++ b/src/core/task-persistence/taskLifecycle.ts @@ -130,3 +130,26 @@ export function abandonDelegatedChild( }, } } + +/** + * Ownership of a restored task's provider-profile pin: the user's global profile + * choice governs a root task, while a delegated child keeps the task-local pin + * delegation assigned it (delegation never changes the global profile). + */ +export type RestoreProfileOrigin = "user" | "delegated-child" + +export function restoredProfileOriginOf(record: Pick): RestoreProfileOrigin { + return record.parentTaskId ? "delegated-child" : "user" +} + +/** + * The one sanctioned way to rewrite a persisted task's profile pin: a copy that + * patches only apiConfigName. A refresh routed through this reducer cannot revert + * newer token counts or timestamps, and cannot serialize the live rootTask/ + * parentTask references the cancel-rehydrate path attaches to history items. + * An absent or empty name keeps the record unchanged, so applying a decision + * without a refresh is a no-op on the persisted record. + */ +export function repinTaskProfilePin(record: HistoryItem, apiConfigName: string | undefined): HistoryItem { + return apiConfigName ? { ...record, apiConfigName } : record +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 542e6bb7682..dfb385ee841 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -25,6 +25,8 @@ import { beginExplicitRecovery, } from "./webviewRecoveryPolicy" +import { resolveRestoreProfileActivation } from "./restore-provider-profile" + import { type TaskProviderLike, type TaskProviderEvents, @@ -152,6 +154,8 @@ import { delegateTaskToChild, interruptDelegatedChild, LifecycleTransitionError, + repinTaskProfilePin, + restoredProfileOriginOf, } from "../task-persistence" import { readTaskMessages } from "../task-persistence/taskMessages" import { readFileWithMissingRetry } from "../task-persistence/readFileWithMissingRetry" @@ -1600,41 +1604,131 @@ export class ClineProvider } } + // Settings snapshot for the Task constructor. On the profile-restore path it is + // captured inside the provider-profile mutation queue, right after the decision's + // activation, so no interleaved user profile switch can leave the task built from + // settings that do not match the decided profile. + let restoredStateSnapshot: Awaited> | undefined + // If the history item has a saved API config name (provider profile), restore it. // This overrides any mode-based config restoration above, because the task's // specific provider profile takes precedence over mode defaults. + // + // The read -> decide -> activate -> settings-capture sequence runs inside the + // provider-profile mutation queue, so a user profile switch cannot interleave + // between the profile snapshot, the decision, and the settings capture (the + // decision would otherwise pin one profile name while the task is built from + // another profile's settings). if (historyItem.apiConfigName && !skipProfileRestoreFromHistory) { - const listApiConfig = await this.providerSettingsManager.listConfig() - // Keep global state/UI in sync with latest profiles for parity with mode restoration above. - await this.updateGlobalState("listApiConfigMeta", listApiConfig) - const profile = listApiConfig.find(({ name }) => name === historyItem.apiConfigName) + // The narrowed pin, captured before the queue closure: historyItem is + // reassigned on the refresh path, so its narrowing does not survive into + // the callback. + const pinnedApiConfigName: string = historyItem.apiConfigName + const restoreOutcome = await this.enqueueProviderProfileMutation( + async (signal) => { + const listApiConfig = await this.providerSettingsManager.listConfig() + // Keep global state/UI in sync with latest profiles for parity with mode restoration above. + await this.updateGlobalState("listApiConfigMeta", listApiConfig) + const profile = listApiConfig.find(({ name }) => name === pinnedApiConfigName) + // The profile active at restore time is the user's latest choice; a pin naming a + // different profile is stale (the task saved it before the switch). Resolving the + // active name against the profile list keeps a dangling pointer out of the decision. + const currentApiConfigName = this.getGlobalState("currentApiConfigName") + const activeProfileName = listApiConfig.some(({ name }) => name === currentApiConfigName) + ? currentApiConfigName + : undefined + // A pinned profile missing from the validated list may still exist in the + // settings file with a schema validation failure; listConfig drops such + // entries, which would make a recoverable profile look deleted. + const pinnedProfileOnDisk = !profile + ? await this.providerSettingsManager.hasRawConfigName(pinnedApiConfigName) + : false + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName, + activeProfileName, + pinnedProfileExists: !!profile, + // A delegated child carries its own task-local profile (delegation never + // changes the global profile), so the global active profile must not win. + profileOrigin: restoredProfileOriginOf(historyItem), + }) - if (profile?.name) { - try { - if (profile.apiProvider) { - await this.activateProviderProfile( - { name: profile.name }, - { - persistModeConfig: false, - persistTaskHistory: false, - expectedCurrentTaskId: historyItem.id, - }, + if (signal.aborted) { + return { decision, pinnedProfileOnDisk, state: await this.getState() } + } + + // Stryker disable next-line OptionalChaining: resolveRestoreProfileActivation returns a reactivation only when pinnedProfileExists holds, and the caller computes that flag as !!profile, so no reachable input distinguishes profile?.name from profile.name + if (decision.reactivateProfileName && profile?.name && profile.apiProvider) { + try { + // Already inside the mutation queue: call the unlocked activation + // directly so the restore does not wait behind itself. + await this.activateProviderProfileUnlocked( + { name: profile.name }, + { + persistModeConfig: false, + persistTaskHistory: false, + expectedCurrentTaskId: historyItem.id, + }, + signal, + ) + } catch (error) { + // Log the error but continue with task restoration. + this.log( + `Failed to restore API configuration '${historyItem.apiConfigName}' for task: ${ + error instanceof Error ? error.message : String(error) + }. Continuing with current configuration.`, + ) + } + } else if (decision.refreshedApiConfigName) { + if (pinnedProfileOnDisk) { + // The pinned profile exists in the settings file but failed validation + // on load, so it is absent from the profile list. Keep the saved name + // and warn instead of overwriting a pin the user may still recover. + this.log( + `Provider profile '${historyItem.apiConfigName}' exists but failed to load. Keeping the saved profile and using the current configuration.`, + ) + } else { + // The pin names a profile that is not in effect at restore time. Keep the user's + // active profile (and its context window) and re-pin the task to it, so later + // restores do not flip the configuration back to the stale profile. + this.log( + `Restoring task ${historyItem.id} with active profile '${decision.refreshedApiConfigName}' instead of stale pinned profile '${historyItem.apiConfigName}'.`, + ) + try { + // Re-pin through the store's own write path: an atomic patch of only + // apiConfigName on the current record, so the refresh can neither + // revert newer token counts with the stale snapshot nor serialize + // the live rootTask/parentTask references the cancel-rehydrate + // path attaches to historyItem. + await this.repinTaskProfile(historyItem.id, decision.refreshedApiConfigName) + } catch (error) { + // The previous task is already evicted here; a failed pin write must not + // abort the restore. Continue with the active configuration and the + // refreshed in-memory pin. + this.log( + `Failed to persist re-pinned profile '${decision.refreshedApiConfigName}' for task ${historyItem.id}: ${ + error instanceof Error ? error.message : String(error) + }. Continuing restore with the active configuration.`, + ) + } + // Local copy for the Task construction only; the store record was + // already re-pinned through repinTaskProfile. + historyItem = { ...historyItem, apiConfigName: decision.refreshedApiConfigName } + } + } else if (!decision.reactivateProfileName) { + // Nothing to reactivate or refresh: warn but continue with the + // current configuration. + this.log( + pinnedProfileOnDisk + ? `Provider profile '${historyItem.apiConfigName}' exists but failed to load. Keeping the saved profile and using the current configuration.` + : `Provider profile '${historyItem.apiConfigName}' from history no longer exists. Using current configuration.`, ) } - } catch (error) { - // Log the error but continue with task restoration. - this.log( - `Failed to restore API configuration '${historyItem.apiConfigName}' for task: ${ - error instanceof Error ? error.message : String(error) - }. Continuing with current configuration.`, - ) - } - } else { - // Profile no longer exists, log warning but continue - this.log( - `Provider profile '${historyItem.apiConfigName}' from history no longer exists. Using current configuration.`, - ) - } + + return { decision, pinnedProfileOnDisk, state: await this.getState() } + }, + { runToCompletion: true }, + ) + restoredStateSnapshot = restoreOutcome.state } else if (historyItem.apiConfigName && skipProfileRestoreFromHistory) { this.log( `Skipping restore of provider profile '${historyItem.apiConfigName}' for task ${historyItem.id} in CLI runtime.`, @@ -1642,7 +1736,7 @@ export class ClineProvider } const { apiConfiguration, enableCheckpoints, checkpointTimeout, experiments, diffFuzzyThreshold } = - await this.getState() + restoredStateSnapshot ?? (await this.getState()) const task = new Task({ provider: this, apiConfiguration, @@ -1676,6 +1770,13 @@ export class ClineProvider } if (oldTask) { + // The old task's final save writes its own pin (saveClineMessages persists + // _taskApiConfigName). Sync it to the restored record's pin first, so the + // abort cannot write the stale profile name back over a refresh that has + // already landed. + if (historyItem.apiConfigName) { + oldTask.setTaskApiConfigName(historyItem.apiConfigName) + } // Abort the old task to stop running processes and mark as abandoned try { await oldTask.abortTask(true) @@ -2462,9 +2563,10 @@ export class ClineProvider async deleteProviderProfile(profileToDelete: ProviderSettingsEntry) { const globalSettings = this.contextProxy.getValues() + const deletedWasActive = profileToDelete.name === globalSettings.currentApiConfigName let profileToActivate: string | undefined = globalSettings.currentApiConfigName - if (profileToDelete.name === profileToActivate) { + if (deletedWasActive) { profileToActivate = this.getProviderProfileEntries().find(({ name }) => name !== profileToDelete.name)?.name } @@ -2480,6 +2582,22 @@ export class ClineProvider listApiConfigMeta: entries, }) + if (deletedWasActive) { + // Deleting the active profile must leave the active name naming the settings + // in effect. Activate the fallback the same way the webview delete path does, + // so a later task restore cannot pin a name whose settings were never loaded + // and run the deleted profile's settings under the new name. + try { + await this.activateProviderProfile({ name: profileToActivate }) + } catch (error) { + this.log( + `Failed to activate profile '${profileToActivate}' after deleting '${profileToDelete.name}': ${ + error instanceof Error ? error.message : String(error) + }. The active name changed but its settings were not loaded.`, + ) + } + } + await this.postStateToWebview() } @@ -3746,6 +3864,38 @@ export class ClineProvider * @param options.broadcast Whether to broadcast the updated history to the webview (default: true) * @returns The updated task history array */ + /** + * Re-pin a task's provider profile through the store's own write path: an atomic + * read-update-write under the store lock that patches only `apiConfigName` on the + * current record. A refresh therefore cannot revert newer token counts or + * timestamps with the caller's stale snapshot, and it cannot serialize the live + * `rootTask`/`parentTask` references that the cancel-rehydrate path attaches to + * the history item copy. The missing-record error, the recent-tasks cache clear + * and the webview update are handled here. + */ + private async repinTaskProfile(taskId: string, apiConfigName: string): Promise { + const patchPin = (current: HistoryItem) => repinTaskProfilePin(current, apiConfigName) + try { + await this.taskHistoryStore.atomicReadAndUpdate(taskId, patchPin) + } catch (error) { + const notCached = + error instanceof Error && + error.message === `[TaskHistoryStore] atomicReadAndUpdate: task ${taskId} not found in cache` + if (!notCached) throw error + // The cache lost the record (an invalidation raced the restore): reload once. + await this.taskHistoryStore.invalidate(taskId) + if (!this.taskHistoryStore.get(taskId)) throw error + await this.taskHistoryStore.atomicReadAndUpdate(taskId, patchPin) + } + this.recentTasksCache = undefined + if (this.isViewLaunched) { + const updatedItem = this.taskHistoryStore.get(taskId) + if (updatedItem) { + await this.postMessageToWebview({ type: "taskHistoryItemUpdated", taskHistoryItem: updatedItem }) + } + } + } + async updateTaskHistory(item: HistoryItem, options: { broadcast?: boolean } = {}): Promise { const { broadcast = true } = options diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 60b5cde8fd7..ee99c027e73 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -583,10 +583,14 @@ describe("ClineProvider - Sticky Provider Profile", () => { apiConfigName: "saved-profile", // Saved provider profile } - // Mock activateProviderProfile to track calls + // The restore decision runs serialized inside the provider-profile mutation + // queue, so activation goes through activateProviderProfileUnlocked: routing + // it through the public activateProviderProfile would enqueue behind itself + // and deadlock the queue (see restore-provider-profile.ts). const activateProviderProfileSpy = vi - .spyOn(provider, "activateProviderProfile") + .fn() .mockResolvedValue(undefined) + provider["activateProviderProfileUnlocked"] = activateProviderProfileSpy // Mock providerSettingsManager.listConfig vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([ @@ -596,10 +600,12 @@ describe("ClineProvider - Sticky Provider Profile", () => { // Initialize task with history item await provider.createTaskWithHistoryItem(historyItem) - // Verify provider profile was restored via activateProviderProfile (restore-only: don't persist mode config) + // Verify provider profile was restored via activateProviderProfileUnlocked + // (restore-only: don't persist mode config; the queue passes its AbortSignal) expect(activateProviderProfileSpy).toHaveBeenCalledWith( { name: "saved-profile" }, { persistModeConfig: false, persistTaskHistory: false, expectedCurrentTaskId: historyItem.id }, + expect.any(AbortSignal), ) }) @@ -783,13 +789,23 @@ describe("ClineProvider - Sticky Provider Profile", () => { apiConfigName: "task-specific-profile", // Task's actual profile } - // Track all activateProviderProfile calls + // Track all profile activations. The mode-based path activates through the + // public activateProviderProfile, while the task's apiConfigName restore + // activates through activateProviderProfileUnlocked inside the provider-profile + // mutation queue, so both seams must be recorded in call order. const activateCalls: string[] = [] vi.spyOn(provider, "activateProviderProfile").mockImplementation(async (args) => { if ("name" in args) { activateCalls.push(args.name) } }) + provider["activateProviderProfileUnlocked"] = vi + .fn() + .mockImplementation(async (args) => { + if ("name" in args) { + activateCalls.push(args.name) + } + }) // Mock providerSettingsManager methods vi.spyOn(provider.providerSettingsManager, "getModeConfigId").mockResolvedValue("mode-config-id") diff --git a/src/core/webview/__tests__/restore-provider-profile.spec.ts b/src/core/webview/__tests__/restore-provider-profile.spec.ts new file mode 100644 index 00000000000..fc43c7103aa --- /dev/null +++ b/src/core/webview/__tests__/restore-provider-profile.spec.ts @@ -0,0 +1,185 @@ +// npx vitest run core/webview/__tests__/restore-provider-profile.spec.ts +// +// Decision-table tests for resolveRestoreProfileActivation, the pure decision at +// the heart of the issue #970 fix ("restore follows the active profile"). +// +// Invariants (one per failure sentence): +// - FollowActive: with an existing pin and a resolvable active profile that +// differs from it, the decision must not reactivate the pinned profile. +// - PinNamesEffect: a refresh must name exactly the active profile, and a +// decision that reactivates must never also refresh. +// - LegacyFallback: with no resolvable active profile, an existing pinned +// profile is reactivated exactly as before the fix. +// - ChildPinStable: a delegated child is never refreshed to the global active +// profile; the child's own task-local pin is the only profile a child +// restore reactivates (PR 2649 human review, restore-provider-profile.ts:66). + +import { describe, it, expect } from "vitest" + +import { + resolveRestoreProfileActivation, + type RestoreProfileDecision, + type RestoreProfileOrigin, +} from "../restore-provider-profile" + +interface DecisionCase { + name: string + pinnedApiConfigName: string | undefined + activeProfileName: string | undefined + pinnedProfileExists: boolean + profileOrigin: RestoreProfileOrigin + expected: RestoreProfileDecision +} + +describe("resolveRestoreProfileActivation", () => { + it.each([ + { + name: "no pin: nothing to reactivate and nothing to refresh", + pinnedApiConfigName: undefined, + activeProfileName: "provider-2", + pinnedProfileExists: false, + profileOrigin: "user", + expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, + }, + { + name: "existing pin with no resolvable active profile: legacy fallback reactivates the pin", + pinnedApiConfigName: "provider-1", + activeProfileName: undefined, + pinnedProfileExists: true, + profileOrigin: "user", + expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, + }, + { + name: "existing pin equal to the active profile: reactivation only, pin preserved", + pinnedApiConfigName: "provider-1", + activeProfileName: "provider-1", + pinnedProfileExists: true, + profileOrigin: "user", + expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, + }, + { + name: "existing pin that differs from the active profile: follow the active profile", + pinnedApiConfigName: "provider-1", + activeProfileName: "provider-2", + pinnedProfileExists: true, + profileOrigin: "user", + expected: { reactivateProfileName: undefined, refreshedApiConfigName: "provider-2" }, + }, + { + name: "deleted pin with no resolvable active profile: leave the configuration untouched", + pinnedApiConfigName: "deleted-profile", + activeProfileName: undefined, + pinnedProfileExists: false, + profileOrigin: "user", + expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, + }, + { + name: "deleted pin with a resolvable active profile: re-pin to the active profile", + pinnedApiConfigName: "deleted-profile", + activeProfileName: "provider-2", + pinnedProfileExists: false, + profileOrigin: "user", + expected: { reactivateProfileName: undefined, refreshedApiConfigName: "provider-2" }, + }, + { + name: "delegated child with its own pin: reactivate the child pin only, never refresh", + pinnedApiConfigName: "provider-1", + activeProfileName: "provider-2", + pinnedProfileExists: true, + profileOrigin: "delegated-child", + expected: { reactivateProfileName: "provider-1", refreshedApiConfigName: undefined }, + }, + { + name: "delegated child whose pin no longer exists: keep the configuration, never re-pin to the global profile", + pinnedApiConfigName: "deleted-profile", + activeProfileName: "provider-2", + pinnedProfileExists: false, + profileOrigin: "delegated-child", + expected: { reactivateProfileName: undefined, refreshedApiConfigName: undefined }, + }, + ])("$name", ({ pinnedApiConfigName, activeProfileName, pinnedProfileExists, profileOrigin, expected }) => { + expect( + resolveRestoreProfileActivation({ + pinnedApiConfigName, + activeProfileName, + pinnedProfileExists, + profileOrigin, + }), + ).toStrictEqual(expected) + }) + + // Property test over the whole input domain (the TLA rules ask for a property + // test from the same invariant sentence; the domain is small enough to check + // exhaustively, which is stronger than sampling). Every combination of pin, + // active profile, existence flag and origin must satisfy the invariant set. + const pins = [undefined, "provider-1", "provider-2", "deleted-profile"] as const + const actives = [undefined, "provider-1", "provider-2"] as const + const exists = [true, false] as const + const origins = ["user", "delegated-child"] as const + + it("satisfies the invariant set for every input in the domain", () => { + const failures: string[] = [] + + for (const pinnedApiConfigName of pins) { + for (const activeProfileName of actives) { + for (const pinnedProfileExists of exists) { + for (const profileOrigin of origins) { + const decision = resolveRestoreProfileActivation({ + pinnedApiConfigName, + activeProfileName, + pinnedProfileExists, + profileOrigin, + }) + const label = `pin=${String(pinnedApiConfigName)} active=${String(activeProfileName)} exists=${String(pinnedProfileExists)} origin=${profileOrigin}` + const refreshes = decision.refreshedApiConfigName !== undefined + const reactivates = decision.reactivateProfileName !== undefined + + // PinNamesEffect holds for both origins: a refresh names exactly the + // active profile, and a reactivation never also refreshes. + if (refreshes && decision.refreshedApiConfigName !== activeProfileName) { + failures.push(`${label}: refresh does not name the active profile`) + } + if (refreshes && reactivates) { + failures.push(`${label}: refresh and reactivation combined`) + } + + if (profileOrigin === "user") { + // FollowActive: an existing pin differing from the resolvable active + // profile is never reactivated. + if ( + pinnedApiConfigName !== undefined && + pinnedProfileExists && + activeProfileName !== undefined && + activeProfileName !== pinnedApiConfigName && + reactivates + ) { + failures.push(`${label}: stale pin reactivated over the active profile`) + } + // LegacyFallback: an existing pin with no resolvable active profile + // is reactivated exactly as before the fix. + if ( + pinnedApiConfigName !== undefined && + pinnedProfileExists && + activeProfileName === undefined && + decision.reactivateProfileName !== pinnedApiConfigName + ) { + failures.push(`${label}: legacy fallback lost the pin reactivation`) + } + } else { + // ChildPinStable: a delegated child is never refreshed to the global + // profile and only ever reactivates its own pin. + if (refreshes) { + failures.push(`${label}: delegated child refreshed to the global profile`) + } + if (reactivates && decision.reactivateProfileName !== pinnedApiConfigName) { + failures.push(`${label}: delegated child reactivated a foreign profile`) + } + } + } + } + } + } + + expect(failures).toStrictEqual([]) + }) +}) diff --git a/src/core/webview/restore-provider-profile.ts b/src/core/webview/restore-provider-profile.ts new file mode 100644 index 00000000000..2e0c10a2615 --- /dev/null +++ b/src/core/webview/restore-provider-profile.ts @@ -0,0 +1,88 @@ +// Restore-profile decision for task restore (issue #970). +// +// When a stopped task is restored, its HistoryItem.apiConfigName pins the provider +// profile the task last ran under. If the user switched to a different profile +// while the task was stopped, blindly re-activating that pin reverts the user's +// choice: the restored task and the task header keep the old provider's context +// window, and the usage bar can exceed 100%. +// +// Invariants (first version written before the fix; see +// docs/architecture/tla/RestoreProfileDecision.tla): +// - FollowActive: with an existing pin and a resolvable active profile that +// differs from it, restore must not reactivate the pinned profile. +// - PinNamesEffect: a pin refresh must name exactly the active profile, and a +// decision that reactivates must never also refresh. +// - LegacyFallback: with no resolvable active profile, an existing pinned +// profile is reactivated exactly as before the change. +// - ChildPinStable: a delegated child's restore never refreshes the child's +// task-local pin to the global active profile and never overwrites it. + +import type { RestoreProfileOrigin } from "../task-persistence/taskLifecycle" + +export type { RestoreProfileOrigin } + +/** A profile to re-activate, or undefined to leave the active configuration untouched. */ +export interface RestoreProfileDecision { + /** Profile to re-activate before constructing the restored task; undefined leaves the current configuration in place. */ + reactivateProfileName: string | undefined + /** Replacement pin for the history item; undefined keeps the stored pin unchanged. */ + refreshedApiConfigName: string | undefined +} + +export interface RestoreProfileInput { + /** The pin recorded on the history item at last save; undefined when absent. */ + pinnedApiConfigName: string | undefined + /** The profile active at restore time (currentApiConfigName); undefined when none resolves. */ + activeProfileName: string | undefined + /** Whether the pinned profile still exists in the profile list. */ + pinnedProfileExists: boolean + /** Whether the pinned task runs a delegated child's task-local profile or the user's global choice. */ + profileOrigin: RestoreProfileOrigin +} + +/** + * Decide how a task restore treats the profile pin stored on its history item. + * + * Rules: + * - No pin: nothing to do; the active configuration stays untouched. + * - Delegated child: the child's own task-local profile (selected at delegation by + * selectHandoffExecutionContext) is authoritative; the child is never re-pinned + * to the global active profile and its saved profile is never overwritten. + * - Pin exists and no active profile resolves: legacy fallback re-activates the pin. + * - Pin exists and equals the active profile: re-activate it (idempotent re-apply + * of the saved profile settings, unchanged behavior for restores without a switch). + * - Pin exists and differs from the active profile: keep the user's active profile + * and refresh the stale pin to it. + * - Pin no longer exists: keep the active configuration; refresh the pin to the + * active profile when one resolves. + */ +export function resolveRestoreProfileActivation(input: RestoreProfileInput): RestoreProfileDecision { + const { pinnedApiConfigName, activeProfileName, pinnedProfileExists, profileOrigin } = input + + if (!pinnedApiConfigName) { + return { reactivateProfileName: undefined, refreshedApiConfigName: undefined } + } + + if (profileOrigin === "delegated-child") { + // Delegation never changes the global profile, so the active global profile is + // not the user's choice for this child: restore the child's own pin (the + // legacy behavior) and never refresh it to the global profile. + if (!pinnedProfileExists) { + return { reactivateProfileName: undefined, refreshedApiConfigName: undefined } + } + return { reactivateProfileName: pinnedApiConfigName, refreshedApiConfigName: undefined } + } + + if (!pinnedProfileExists) { + // The pinned profile is gone; the active configuration (if any) is what runs. + return { reactivateProfileName: undefined, refreshedApiConfigName: activeProfileName } + } + + if (!activeProfileName || activeProfileName === pinnedApiConfigName) { + // No switch happened since the save: re-apply the saved profile settings as before. + return { reactivateProfileName: pinnedApiConfigName, refreshedApiConfigName: undefined } + } + + // The user switched profiles while the task was stopped; their choice wins. + return { reactivateProfileName: undefined, refreshedApiConfigName: activeProfileName } +}