Skip to content

Commit ba2e9db

Browse files
fix(activate,extension): keep a live tab and the snapshot profile through a rollback
Three review rows on the same path: - registerCommands.ts: a Zoo Code tab open behind another editor in its group is neither active nor visible, so the dispose handler cleared the tracked ref while a live tab still existed, contradicting the comment right above it. openClineInNewTab then skipped its reuse path and focusInput targeted the sidebar. The fallback now takes any live tab; only an empty set clears the ref. - extension/api.ts: previousProfileName came from the replay map, which holds only the keys this call wrote. A payload that never carried currentApiConfigName therefore defaulted the name to "default", refreshing the overlays pinned to "default" with this profile settings and skipping the credential replay for the profile that was actually active. It now reads the snapshot, which is the same value whenever the payload did write the pin. - api-configuration.spec.ts: the compensation-time id mismatch had no test on its reject path. A case now creates the name, lets another locked writer replace the record under its own id between the sections, and fails the mode write: deleteConfig is not called and the record keeps the other view id and secret. With the guard removed the case fails with "expected the mock to not be called at all, but actually been called 1 times", so it is the case the guard needed. Measured before the changes: the hidden-tab case failed with "expected undefined to be { marker: 'panel-A' }" and the omitted-pin case failed with savedProfileName "default" instead of "my-profile". registerCommands.spec.ts 63 passed, api-configuration.spec.ts 22 passed, tsc 0 errors, eslint 0 problems, prettier clean, no suppression changes.
1 parent ce3b00a commit ba2e9db

4 files changed

Lines changed: 195 additions & 3 deletions

File tree

‎src/activate/__tests__/registerCommands.spec.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,6 +1109,52 @@ describe("openClineInNewTab", () => {
11091109
expect(getPanel()).toBeUndefined()
11101110
})
11111111

1112+
it("keeps a hidden live tab as the tracked ref when the tracked panel closes", async () => {
1113+
// A Zoo Code tab that sits open behind another editor in its group is neither active nor
1114+
// visible. It is still a live tab, so the tracked ref must keep resolving the tab-scoped
1115+
// commands and focusInput at it - clearing the reference is for when nothing remains.
1116+
const panelA = Object.assign({} as vscode.WebviewPanel, {
1117+
marker: "panel-A",
1118+
webview: { postMessage: vi.fn() },
1119+
onDidChangeViewState: vi.fn(),
1120+
onDidDispose: vi.fn(),
1121+
})
1122+
;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelA)
1123+
await openClineInNewTab({
1124+
context: mockContext,
1125+
outputChannel: mockOutputChannel,
1126+
webviewFocusTracker: new WebviewFocusTracker(),
1127+
})
1128+
1129+
const panelB = Object.assign({} as vscode.WebviewPanel, {
1130+
marker: "panel-B",
1131+
webview: { postMessage: vi.fn() },
1132+
onDidChangeViewState: vi.fn(),
1133+
onDidDispose: vi.fn(),
1134+
})
1135+
;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelB)
1136+
await openClineInNewTab({
1137+
context: mockContext,
1138+
outputChannel: mockOutputChannel,
1139+
webviewFocusTracker: new WebviewFocusTracker(),
1140+
})
1141+
Object.assign(panelB, { active: true, visible: true })
1142+
;(panelB.onDidChangeViewState as Mock).mock.calls[0]![0]!({ webviewPanel: panelB })
1143+
expect(getPanel()).toBe(panelB)
1144+
1145+
// Closing the tracked panel leaves only the hidden tab: neither flag is set on it.
1146+
const disposeB = (panelB.onDidDispose as Mock).mock.calls[0]![0] as () => void
1147+
disposeB()
1148+
expect(panelA.active).toBeUndefined()
1149+
expect(panelA.visible).toBeUndefined()
1150+
expect(getPanel()).toBe(panelA)
1151+
1152+
// Closing that tab too leaves nothing live, and only then is the ref cleared.
1153+
const disposeA = (panelA.onDidDispose as Mock).mock.calls[0]![0] as () => void
1154+
disposeA()
1155+
expect(getPanel()).toBeUndefined()
1156+
})
1157+
11121158
it("prefers the active panel over a merely visible one when re-pointing the tracked tab ref", async () => {
11131159
// Panel A is created and tracked first and stays merely visible...
11141160
const panelA = Object.assign({} as vscode.WebviewPanel, {

‎src/activate/registerCommands.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,9 +459,14 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
459459
// when nothing remains. The identity guard above keeps a late
460460
// disposal of an already-replaced panel from clobbering the
461461
// replacement's ref.
462+
const live = [...liveTabPanels]
462463
const remaining =
463-
[...liveTabPanels].find((panel) => panel.active) ??
464-
[...liveTabPanels].find((panel) => panel.visible)
464+
live.find((panel) => panel.active) ??
465+
live.find((panel) => panel.visible) ??
466+
// A tab open behind another editor in its group is neither active nor visible,
467+
// and it is still a live tab: keep the ref on it so the tab-scoped commands and
468+
// focusInput still resolve an instance. Only an empty set clears the ref.
469+
live[0]
465470
setPanel(remaining, "tab")
466471
}
467472
},

‎src/extension/__tests__/api-configuration.spec.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,79 @@ describe("API - configuration", () => {
642642
expect(postStateToWebview).not.toHaveBeenCalled()
643643
})
644644

645+
it("keeps a record another view rewrote between the save and the compensation", async () => {
646+
// The reject path of the id comparison. This call creates the name, so its own rollback
647+
// would delete it; a locked writer that replaces the record in between owns the name now,
648+
// and deleting it here would remove that other view record together with its secret. The
649+
// store is live-backed so the re-read inside the section sees the rewrite, which a static
650+
// hasConfig mock cannot model.
651+
const records = new Map<string, { id: string; settings: Record<string, unknown> }>()
652+
const hasConfig = vi.fn((name: string) => Promise.resolve(records.has(name)))
653+
const getProfile = vi.fn(({ name }: { name: string }) => {
654+
const entry = records.get(name)
655+
return entry
656+
? Promise.resolve({ name, id: entry.id, ...entry.settings })
657+
: Promise.reject(new Error(`Profile "${name}" does not exist`))
658+
})
659+
const saveConfig = vi.fn((name: string, settings: Record<string, unknown>) => {
660+
records.set(name, { id: "this-call-id", settings })
661+
return Promise.resolve("this-call-id")
662+
})
663+
const deleteConfig = vi.fn((name: string) => {
664+
records.delete(name)
665+
return Promise.resolve()
666+
})
667+
const setModeConfig = vi.fn(async () => {
668+
// The interleaving the guard is for: another locked writer replaces the record this
669+
// call had created, under its own id.
670+
records.set("pinned", { id: "other-view-id", settings: { apiKey: "other-view-secret" } })
671+
throw new Error("mode write failed")
672+
})
673+
const setValues = vi.fn().mockResolvedValue(undefined)
674+
const postStateToWebview = vi.fn().mockResolvedValue(undefined)
675+
const provider = {
676+
context: {},
677+
on: vi.fn(),
678+
log: vi.fn(),
679+
getProviderProfileEntries: vi.fn().mockReturnValue([]),
680+
getValues: vi.fn(() => ({ currentApiConfigName: "pinned" })),
681+
setValues,
682+
contextProxy: {
683+
getValue: vi.fn().mockReturnValue(undefined),
684+
setValues: vi.fn().mockResolvedValue(undefined),
685+
getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.anthropic }),
686+
setProviderSettings: vi.fn().mockResolvedValue(undefined),
687+
},
688+
refreshViewLocalStateForUpdatedProfile: vi.fn().mockResolvedValue(undefined),
689+
providerSettingsManager: {
690+
runExclusiveAcrossInstances: runManagerSectionInline,
691+
hasConfig,
692+
getProfile,
693+
saveConfig,
694+
deleteConfig,
695+
setModeConfig,
696+
getModeConfigId: vi.fn().mockResolvedValue(undefined),
697+
},
698+
postStateToWebview,
699+
} as unknown as ClineProvider
700+
const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel
701+
const api = new API(outputChannel, provider, makeClineProviderFactory())
702+
703+
await expect(
704+
api.setConfiguration({ currentApiConfigName: "pinned", modeApiConfigs: { code: "new-code-config" } }),
705+
).rejects.toThrow("mode write failed")
706+
707+
// The existence check saw the name absent, so the rollback reaches the delete branch; the
708+
// id its own save returned is not the id on the record any more, and the record stays.
709+
expect(deleteConfig).not.toHaveBeenCalled()
710+
expect(records.get("pinned")).toEqual({
711+
id: "other-view-id",
712+
settings: expect.objectContaining({ apiKey: "other-view-secret" }),
713+
})
714+
expect(saveConfig).toHaveBeenCalledTimes(1)
715+
expect(postStateToWebview).not.toHaveBeenCalled()
716+
})
717+
645718
it("replays only the keys this call wrote and leaves keys another view changed alone", async () => {
646719
// A rollback may restore what this call changed and nothing else, because anything the
647720
// snapshot happens to hold otherwise belongs to a writer that has moved on since it was
@@ -843,6 +916,68 @@ describe("API - configuration", () => {
843916
expect(postStateToWebview).not.toHaveBeenCalled()
844917
})
845918

919+
it("names the profile the snapshot was on when the payload never carried the pin", async () => {
920+
// Which profile the views return to has to come from the snapshot the call captured. The
921+
// replay map only holds the keys this call wrote, so a payload that never carried
922+
// currentApiConfigName leaves the pin out of it: defaulting the name there refreshes the
923+
// overlays pinned to "default" with another profile settings and skips the credential
924+
// replay for the profile that was actually active.
925+
const store: Record<string, unknown> = {
926+
currentApiConfigName: "my-profile",
927+
apiProvider: providerIdentifiers.openrouter,
928+
}
929+
const setValues = vi.fn().mockResolvedValue(undefined)
930+
const profileStore = makeProfileStoreDouble({
931+
"my-profile": {
932+
id: "my-id",
933+
settings: { apiProvider: providerIdentifiers.openrouter, apiKey: "my-profile-key" },
934+
},
935+
})
936+
const setModeConfig = vi.fn().mockRejectedValue(new Error("mode write failed"))
937+
const refreshSpy = vi.fn().mockResolvedValue(undefined)
938+
const postStateToWebview = vi.fn().mockResolvedValue(undefined)
939+
const provider = {
940+
context: {},
941+
on: vi.fn(),
942+
log: vi.fn(),
943+
getProviderProfileEntries: vi.fn().mockReturnValue([{ name: "my-profile", id: "my-id" }]),
944+
// Live-backed so the snapshot is this view of the store at snapshot time.
945+
getValues: vi.fn(() => ({ ...store })),
946+
setValues,
947+
contextProxy: {
948+
getValue: vi.fn().mockReturnValue(undefined),
949+
setValues: vi.fn().mockResolvedValue(undefined),
950+
getProviderSettings: vi.fn().mockReturnValue({ apiProvider: providerIdentifiers.openrouter }),
951+
setProviderSettings: vi.fn().mockResolvedValue(undefined),
952+
},
953+
refreshViewLocalStateForUpdatedProfile: refreshSpy,
954+
providerSettingsManager: {
955+
runExclusiveAcrossInstances: runManagerSectionInline,
956+
hasConfig: profileStore.hasConfig,
957+
getProfile: profileStore.getProfile,
958+
saveConfig: profileStore.saveConfig,
959+
deleteConfig: profileStore.deleteConfig,
960+
setModeConfig,
961+
getModeConfigId: vi.fn().mockResolvedValue(undefined),
962+
},
963+
postStateToWebview,
964+
} as unknown as ClineProvider
965+
const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel
966+
const api = new API(outputChannel, provider, makeClineProviderFactory())
967+
968+
// A payload that changes only a model setting: this call never touched the profile pin.
969+
await expect(
970+
api.setConfiguration({ apiModelId: "gpt-5-codex", modeApiConfigs: { code: "new-code-config" } }),
971+
).rejects.toThrow("mode write failed")
972+
973+
// The saved profile falls back to "default" because the payload omitted the pin, but the
974+
// profile the overlays must be considered on again is the one the snapshot names, and that
975+
// profile overlays must be replayed from its own record.
976+
expect(setValues).toHaveBeenLastCalledWith(expect.any(Object), { savedProfileName: "my-profile" })
977+
expect(refreshSpy).toHaveBeenCalledWith("my-profile", expect.objectContaining({ apiKey: "my-profile-key" }))
978+
expect(postStateToWebview).not.toHaveBeenCalled()
979+
})
980+
846981
describe("the display settings", () => {
847982
const setup = () => {
848983
const setValues = vi.fn().mockResolvedValue(undefined)

‎src/extension/api.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,13 @@ export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI {
776776
const replayValues: RooCodeSettings = Object.fromEntries(
777777
Object.entries(snapshotValues).filter(([key]) => writtenKeys.has(key)),
778778
)
779-
const previousProfileName = replayValues.currentApiConfigName || "default"
779+
// Which profile the views return to is read from the snapshot, not from the replay
780+
// filter: a payload that never wrote currentApiConfigName leaves the pin out of the
781+
// replay, and defaulting it here would refresh the overlays pinned to "default" with
782+
// this profile settings and skip the credential replay for the profile that was
783+
// actually active. When the payload did write the pin the two readings are the same
784+
// value, because the replay holds the snapshot value for every key it carries.
785+
const previousProfileName = snapshotValues.currentApiConfigName || "default"
780786
try {
781787
await this.sidebarProvider.setValues(replayValues, { savedProfileName: previousProfileName })
782788
} catch (restoreError) {

0 commit comments

Comments
 (0)