Skip to content

Commit d34a654

Browse files
Merge branch 'vps2/f6-e2e-viewstate' (cef38f5, #1565) into vps2/f7-viewstate-loaded
The previous merge of 9a600f5 was discarded and this one rebuilt on the refreshed #1565 head, which now sits on the finished #1562 head ba2e9db (rollback profile name from the snapshot, the live-tab fallback, and the two regression cases). #1562 content already ported here is not duplicated: the delta from 9a600f5 to cef38f5 is applied onto the previously resolved result, so this branch resolutions for the view-state machinery are kept.
2 parents d76f001 + cef38f5 commit d34a654

7 files changed

Lines changed: 614 additions & 112 deletions

File tree

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

Lines changed: 60 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ describe("registerCommands handlers", () => {
168168

169169
beforeEach(() => {
170170
vi.clearAllMocks()
171+
172+
// vi.clearAllMocks drops call history but keeps implementations, so a per-view
173+
// lookup installed by an earlier test would still be in place here. Clear it so
174+
// each test decides its own routing instead of inheriting the previous one.
175+
;(ClineProvider.getInstanceForView as Mock).mockReset()
171176
handlers = {}
172177

173178
mockOutputChannel = {
@@ -685,9 +690,7 @@ describe("registerCommands handlers", () => {
685690
it("focusInput logs the drop when a tab panel is tracked without a live tab instance", async () => {
686691
setPanel({} as vscode.WebviewView, "sidebar")
687692
setPanel({} as vscode.WebviewPanel, "tab")
688-
// No live instance for the tracked panel: clear the return value the previous
689-
// InTab test left on this mock so the tab path resolves no provider.
690-
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined)
693+
// No live instance for the tracked panel, so the tab path resolves no provider.
691694

692695
await handlers["zoo-code.focusInput"]()
693696

@@ -699,6 +702,14 @@ describe("registerCommands handlers", () => {
699702
"focusInput: no live provider for the tracked tab panel; action dropped",
700703
)
701704
})
705+
706+
// Determinism guard: vi.clearAllMocks keeps mockImplementation, so an implementation
707+
// installed by an earlier handler test would decide which provider a later test
708+
// resolves. The lookup must enter every test unset - this case fails on the residue of
709+
// the tests above it, not on any behaviour of its own.
710+
it("enters each test with no installed per-view provider lookup", () => {
711+
expect((ClineProvider.getInstanceForView as Mock).getMockImplementation()).toBeUndefined()
712+
})
702713
})
703714

704715
describe("openClineInNewTab", () => {
@@ -1130,6 +1141,52 @@ describe("openClineInNewTab", () => {
11301141
expect(getPanel()).toBeUndefined()
11311142
})
11321143

1144+
it("keeps a hidden live tab as the tracked ref when the tracked panel closes", async () => {
1145+
// A Zoo Code tab that sits open behind another editor in its group is neither active nor
1146+
// visible. It is still a live tab, so the tracked ref must keep resolving the tab-scoped
1147+
// commands and focusInput at it - clearing the reference is for when nothing remains.
1148+
const panelA = Object.assign({} as vscode.WebviewPanel, {
1149+
marker: "panel-A",
1150+
webview: { postMessage: vi.fn() },
1151+
onDidChangeViewState: vi.fn(),
1152+
onDidDispose: vi.fn(),
1153+
})
1154+
;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelA)
1155+
await openClineInNewTab({
1156+
context: mockContext,
1157+
outputChannel: mockOutputChannel,
1158+
webviewFocusTracker: new WebviewFocusTracker(),
1159+
})
1160+
1161+
const panelB = Object.assign({} as vscode.WebviewPanel, {
1162+
marker: "panel-B",
1163+
webview: { postMessage: vi.fn() },
1164+
onDidChangeViewState: vi.fn(),
1165+
onDidDispose: vi.fn(),
1166+
})
1167+
;(vscode.window.createWebviewPanel as Mock).mockReturnValueOnce(panelB)
1168+
await openClineInNewTab({
1169+
context: mockContext,
1170+
outputChannel: mockOutputChannel,
1171+
webviewFocusTracker: new WebviewFocusTracker(),
1172+
})
1173+
Object.assign(panelB, { active: true, visible: true })
1174+
;(panelB.onDidChangeViewState as Mock).mock.calls[0]![0]!({ webviewPanel: panelB })
1175+
expect(getPanel()).toBe(panelB)
1176+
1177+
// Closing the tracked panel leaves only the hidden tab: neither flag is set on it.
1178+
const disposeB = (panelB.onDidDispose as Mock).mock.calls[0]![0] as () => void
1179+
disposeB()
1180+
expect(panelA.active).toBeUndefined()
1181+
expect(panelA.visible).toBeUndefined()
1182+
expect(getPanel()).toBe(panelA)
1183+
1184+
// Closing that tab too leaves nothing live, and only then is the ref cleared.
1185+
const disposeA = (panelA.onDidDispose as Mock).mock.calls[0]![0] as () => void
1186+
disposeA()
1187+
expect(getPanel()).toBeUndefined()
1188+
})
1189+
11331190
it("prefers the active panel over a merely visible one when re-pointing the tracked tab ref", async () => {
11341191
// Panel A is created and tracked first and stays merely visible...
11351192
const panelA = Object.assign({} as vscode.WebviewPanel, {
@@ -1720,53 +1777,6 @@ describe("openClineInNewTab", () => {
17201777
__resetLiveTabPanelsForTests()
17211778
})
17221779

1723-
it.each([false, true])(
1724-
"clears a closed tab reference only if it is still current (replacement: %s)",
1725-
async (replaced) => {
1726-
await openClineInNewTab({
1727-
context: mockContext,
1728-
outputChannel: mockOutputChannel,
1729-
webviewFocusTracker: new WebviewFocusTracker(),
1730-
})
1731-
const panel = vi.mocked(vscode.window.createWebviewPanel).mock.results[0].value
1732-
const onDispose = vi.mocked(panel.onDidDispose).mock.calls[0][0]
1733-
const replacement = { ...panel }
1734-
if (replaced) setPanel(replacement, "tab")
1735-
1736-
onDispose()
1737-
1738-
expect(getPanel()).toBe(replaced ? replacement : undefined)
1739-
},
1740-
)
1741-
1742-
it("creates a webview panel with title 'Zoo Code'", async () => {
1743-
// Pin the MdmService sentinel locally: the module mock's implementation leaks
1744-
// across describes once another test set it, so the constructor's sixth
1745-
// argument must be asserted against a deterministic double.
1746-
const mockMdm = Object.assign({} as MdmService, { name: "mock-mdm" })
1747-
;(MdmService.getInstance as Mock).mockReturnValue(mockMdm)
1748-
const webviewFocusTracker = new WebviewFocusTracker()
1749-
await openClineInNewTab({ context: mockContext, outputChannel: mockOutputChannel, webviewFocusTracker })
1750-
expect(ClineProvider).toHaveBeenCalledWith(
1751-
mockContext,
1752-
mockOutputChannel,
1753-
"editor",
1754-
await ContextProxy.getInstance(mockContext),
1755-
webviewFocusTracker,
1756-
mockMdm,
1757-
)
1758-
1759-
expect(vscode.window.createWebviewPanel).toHaveBeenCalledWith(
1760-
"zoo-code.TabPanelProvider",
1761-
"Zoo Code",
1762-
expect.any(Number),
1763-
expect.objectContaining({
1764-
enableScripts: true,
1765-
retainContextWhenHidden: true,
1766-
}),
1767-
)
1768-
})
1769-
17701780
it("cleans up the tracked refs and disposes the provider when initialization fails", async () => {
17711781
const resolveSpy = vi
17721782
.spyOn(ClineProvider.prototype, "resolveWebviewView")
@@ -1808,35 +1818,6 @@ describe("openClineInNewTab", () => {
18081818
disposeSpy.mockRestore()
18091819
})
18101820

1811-
it("preserves the initialization error when provider cleanup also fails", async () => {
1812-
const resolveSpy = vi
1813-
.spyOn(ClineProvider.prototype, "resolveWebviewView")
1814-
.mockRejectedValue(new Error("init failed"))
1815-
// A throwing MCP disposable inside dispose() rejects the cleanup await;
1816-
// that rejection must not replace the initialization error the caller
1817-
// sees (deregistration itself already ran in dispose()'s finally path).
1818-
const disposeSpy = vi.spyOn(ClineProvider.prototype, "dispose").mockRejectedValue(new Error("cleanup boom"))
1819-
;(vscode.window.createWebviewPanel as Mock).mockReturnValue(
1820-
Object.assign({} as vscode.WebviewPanel, {
1821-
webview: { postMessage: vi.fn() },
1822-
onDidChangeViewState: vi.fn(),
1823-
onDidDispose: vi.fn(),
1824-
dispose: vi.fn(),
1825-
}),
1826-
)
1827-
1828-
await expect(
1829-
openClineInNewTab({
1830-
context: mockContext,
1831-
outputChannel: mockOutputChannel,
1832-
webviewFocusTracker: new WebviewFocusTracker(),
1833-
}),
1834-
).rejects.toThrow("init failed")
1835-
1836-
resolveSpy.mockRestore()
1837-
disposeSpy.mockRestore()
1838-
})
1839-
18401821
it("re-points the tracked tab at the surviving panel when a new panel's initialization fails", async () => {
18411822
// Panel A opens fully and becomes the tracked tab.
18421823
const panelA = Object.assign({} as vscode.WebviewPanel, {

‎src/activate/registerCommands.ts‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -381,9 +381,6 @@ export const openClineInNewTab = async (options: OpenClineInNewTabOptions) => {
381381
// Clear once settled (success or failure) so the next call starts
382382
// fresh: the reuse path in createTabPanelUnlocked then takes over
383383
// for the tracked panel. Guard the clear so this settlement cannot
384-
// clobber a replacement already stored in the slot. That clobber is
385-
// unreachable in single-threaded settlement order: while the slot
386-
// holds this in-flight creation, every other caller receives that
387384
// clobber a replacement already stored in the slot. A joining caller
388385
// that woke on the disposed creation can reach the slot first - it
389386
// re-enters the loop, sees the slot empty, and stores its own
@@ -510,17 +507,20 @@ export const createClineTabPanel = async ({
510507
() => {
511508
liveTabPanels.delete(newPanel)
512509
if (tabPanel === newPanel) {
513-
// Re-point the tracked ref at the best remaining live tab: an active
514-
// panel first, then a visible one, then any remaining panel — a panel
515-
// can be open but hidden behind another editor group (neither active
516-
// nor visible), and clearing the tracked ref here would let the next
517-
// open create a second panel instead of revealing the one already
518-
// serving a task. The identity guard above keeps a late disposal of an
519-
// already-replaced panel from clobbering the replacement's ref.
510+
// Re-point the tracked ref at a remaining live tab (active first,
511+
// then visible) so the tab-scoped title-bar commands and
512+
// focusInput keep resolving an instance; clear the ref as before
513+
// when nothing remains. The identity guard above keeps a late
514+
// disposal of an already-replaced panel from clobbering the
515+
// replacement's ref.
516+
const live = [...liveTabPanels]
520517
const remaining =
521-
[...liveTabPanels].find((panel) => panel.active) ||
522-
[...liveTabPanels].find((panel) => panel.visible) ||
523-
[...liveTabPanels][0]
518+
live.find((panel) => panel.active) ??
519+
live.find((panel) => panel.visible) ??
520+
// A tab open behind another editor in its group is neither active nor visible,
521+
// and it is still a live tab: keep the ref on it so the tab-scoped commands and
522+
// focusInput still resolve an instance. Only an empty set clears the ref.
523+
live[0]
524524
setPanel(remaining, "tab")
525525
}
526526
},

‎src/core/webview/ClineProvider.ts‎

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,14 @@ export class ClineProvider
530530
return this.viewLocalState.currentApiConfigName
531531
}
532532

533+
/**
534+
* This view's pinned mode slug from the view-local buffer, or undefined when the view
535+
* follows the shared selection. Exposed so a custom-mode deletion can key the reset
536+
* onto the view it actually applies to instead of moving every view's pin.
537+
*/
538+
get pinnedModeName(): string | undefined {
539+
return this.viewLocalState.mode
540+
}
533541
public isViewLaunched = false
534542
public settingsImportedAt?: number
535543
public readonly latestAnnouncementId = "oct-2026-v3.94.0-models-oauth-chat" // v3.94.0 model support, MCP OAuth, and chat reliability
@@ -1706,12 +1714,13 @@ export class ClineProvider
17061714
// release steps, the first error is preserved, and it is reported once
17071715
// every step has run.
17081716
let cleanupError: unknown
1709-
void this.loadViewState()
17101717

17111718
const cleanupStep = async (label: string, fn: () => unknown | Promise<unknown>) => {
17121719
// #1562 seam: the constructor's `void this.loadViewState()` (construction-time hydrate)
17131720
// is the other #1562 consumer of the delivery signal; it has no caller to report to, so
1714-
// a false return there is intentionally dropped - the dispose-time load below re-runs it.
1721+
// a false return there is intentionally dropped. Disposal does not re-hydrate: there is
1722+
// no live view left to deliver to, and a load started here would mutate the view-local
1723+
// state while the teardown is already running.
17151724
try {
17161725
await fn()
17171726
} catch (error) {
@@ -1805,13 +1814,9 @@ export class ClineProvider
18051814
await cleanupStep("taskHistoryStore", () => this.taskHistoryStore.dispose())
18061815

18071816
this.log("Disposed all disposables")
1808-
ClineProvider.activeInstances.delete(this)
1809-
this.diagnosticsRequestBroker.dispose()
1810-
1811-
// Clean up any event listeners attached to this provider
1812-
this.removeAllListeners()
1813-
1814-
McpServerManager.unregisterProvider(this)
1817+
// The releases themselves live in dispose's finally, not here: the body used to duplicate
1818+
// all four after this log, so every dispose ran the broker release, the listener removal
1819+
// and the MCP unregistration twice.
18151820

18161821
if (cleanupError !== undefined) {
18171822
throw cleanupError
@@ -3673,11 +3678,21 @@ export class ClineProvider
36733678
// do not rehydrate a missing profile name after a reload.
36743679
await this.repointPersistedViewStates(profileToDelete.name, profileToActivate)
36753680

3676-
const viewPinsDeletedProfile =
3681+
// Whether this deletion has to re-anchor this view onto the replacement. The second leg
3682+
// is a view whose own pin names the deleted profile. The first leg is narrower than it
3683+
// reads: a view with no pin of its own does not resolve to the deleted profile, it
3684+
// follows the shared selection, and the deletion hands that selection to it through
3685+
// activation regardless of which profile was removed - the same hand-off the manager
3686+
// gate and the current task handler depend on. Measured both deletions: with the shared
3687+
// selection pointing at a survivor, deleting an unrelated profile still activates the
3688+
// selection for this view and leaves it pinned to it; deleting the profile the selection
3689+
// names activates the replacement. Either way what the view serves afterwards is the
3690+
// profile the shared store holds.
3691+
const viewFollowsDeletedProfile =
36773692
this.viewLocalState.currentApiConfigName === undefined ||
36783693
this.viewLocalState.currentApiConfigName === profileToDelete.name
36793694

3680-
if (viewPinsDeletedProfile) {
3695+
if (viewFollowsDeletedProfile) {
36813696
// Apply the replacement through the activation path so this view's
36823697
// viewLocalState.apiConfiguration and the current task's api handler are
36833698
// refreshed; a name-only update would leave the deleted profile's settings

0 commit comments

Comments
 (0)