Skip to content

Commit be39ce4

Browse files
Merge vps2-f2a (4719931) into vps2-f2c
The previous merge commit (e8b2ac0) was discarded rather than amended, and this merge was created fresh from the finished parent head so the deletion-post fix, the failed-creation survivor hand-back and the test-hygiene resets reach this head without rewriting this unit's own commits. Resolution, and the dedupe that goes with it: the parent's content was already ported into this branch's tree, so re-resolving from scratch would have duplicated it. Checked by blob hash (git rev-parse ":<file>" against git rev-parse <rev>:<file>, pipeline-free): - src/core/webview/__tests__/ClineProvider.spec.ts - resolved to the parent's blob (c62866e...), identical to vps2-f2a; this unit's variant of that file is superseded. - src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts - likewise the parent's blob (bb12bff...); this unit's version was unchanged from its base. - src/core/webview/webviewMessageHandler.ts and its spec - unchanged from the discarded merge's blobs (8709765..., d2987e9...): the parent head did not touch them, so nothing was re-merged. - src/eslint-suppressions.json (69b0804...) and src/core/config/__tests__/ContextProxy.globalStateRestore.spec.ts (da408dc...) - byte-identical to both parents and to the discarded merge, so no variant crept back. - src/activate/registerCommands.ts, activate/__tests__/registerCommands.spec.ts and core/webview/ClineProvider.ts carry the settled content plus the parent's new edits, taken from the discarded merge's resolved text rather than re-resolved from scratch, so the already-ported survivor and rollback content is not re-added. Delta proof: this tree differs from the discarded merge by exactly the parent head's delta - 5 files, +249/-45 against the parent head's +248/-46, with matching per-file line counts (120/4/22/131/17); the single-line difference is a prettier re-wrap of one inserted line in the merged copy of registerCommands.spec.ts. Gates: tsc clean, eslint clean, prettier --check clean. Focused runs on the merged tree: registerCommands.spec 78 passed, ClineProvider.spec 500, ClineProvider.sticky-profile 26. Full suite 45 failed | 12816 passed | 37 skipped - 40 in __tests__/dist_assets.spec.ts (no built dist) and 5 in services/rules/__tests__/rules.spec.ts (Windows symlinks), the same environmental classes as the base. src/core/task/Task.spec.ts is a known inter-run flake; it did not fail in this run.
2 parents a691f24 + 4719931 commit be39ce4

7 files changed

Lines changed: 772 additions & 32 deletions

File tree

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

Lines changed: 311 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,29 @@ vi.mock("../../services/ripgrep/diagnostic", () => ({
131131
registerRipgrepDiagnosticCommand: vi.fn().mockReturnValue({ dispose: vi.fn() }),
132132
}))
133133

134+
// A tab panel double: shaped the way the survivor rule reads a panel - active and visible
135+
// state plus the registration hooks the creation path installs - so a test asserts against
136+
// panel identity rather than structure.
137+
const makeTabPanel = (title: string, viewState: { active: boolean; visible: boolean }): vscode.WebviewPanel => ({
138+
viewType: "zoo-code.TabPanelProvider",
139+
title,
140+
webview: {
141+
options: {},
142+
html: "",
143+
cspSource: "test-webview",
144+
postMessage: vi.fn().mockResolvedValue(true),
145+
onDidReceiveMessage: vi.fn(),
146+
asWebviewUri: vi.fn((uri) => uri),
147+
},
148+
options: {},
149+
viewColumn: vscode.ViewColumn.Two,
150+
...viewState,
151+
onDidChangeViewState: vi.fn(),
152+
onDidDispose: vi.fn(),
153+
reveal: vi.fn(),
154+
dispose: vi.fn(),
155+
})
156+
134157
describe("getVisibleProviderOrLog", () => {
135158
let mockOutputChannel: vscode.OutputChannel
136159

@@ -245,6 +268,11 @@ describe("registerCommands handlers", () => {
245268
// Reset module-level panel state to prevent leakage between tests.
246269
setPanel(undefined, "sidebar")
247270
setPanel(undefined, "tab")
271+
// vi.clearAllMocks drops call history but keeps implementations, so an
272+
// implementation installed on either static registry lookup would otherwise leak into
273+
// every later test and make its result depend on execution order.
274+
;(ClineProvider.getInstanceForView as Mock).mockReset()
275+
;(ClineProvider.getAllInstances as Mock).mockReset().mockReturnValue([])
248276
})
249277

250278
it("registers the ripgrep diagnostic command and stores its disposable in context.subscriptions", async () => {
@@ -626,6 +654,216 @@ describe("registerCommands handlers", () => {
626654
expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" })
627655
})
628656

657+
// Two tab panels can be open at once and the tracker follows whichever one the user
658+
// activates: the onDidChangeViewState wiring in openClineInNewTab
659+
// (registerCommands.ts:492-508) says so outright and re-points on activation. Disposal
660+
// has to make the same choice deliberately, because focusInput reads the tracker
661+
// (255-273) and getPanel falls back to the sidebar (47-49): a cleared tracker with a
662+
// live panel left behind sends the next ordinary "Open in editor" to a third panel
663+
// instead of the one that is still on screen.
664+
//
665+
// The pool the survivor is chosen from is the instance registry, because closing a
666+
// panel disposes its provider and ClineProvider.dispose unregisters the instance
667+
// synchronously at its start (ClineProvider.ts:1653-1659). These tests model liveness
668+
// the same way: a view is live while a map entry for it exists, and disposing a tab
669+
// removes that entry.
670+
671+
let providersByView: Map<vscode.WebviewView | vscode.WebviewPanel, ClineProvider>
672+
const liveInstances = (): ClineProvider[] => [...providersByView.values()]
673+
674+
// View -> live instance, which is the lookup getInstanceForView performs
675+
// (ClineProvider.ts:1754-1756), so the tab provider is resolved by panel identity.
676+
const startInstanceRegistry = () => {
677+
providersByView = new Map()
678+
;(ClineProvider.getInstanceForView as Mock).mockImplementation(
679+
(view: vscode.WebviewView | vscode.WebviewPanel) => providersByView.get(view),
680+
)
681+
;(ClineProvider.getAllInstances as Mock).mockImplementation(liveInstances)
682+
}
683+
684+
/**
685+
* Open one tab panel through the shipped creation path and register the provider the
686+
* automocked ClineProvider constructor produced for it. forceNew is how two live tab
687+
* panels happen today: startNewTask({ newTab: true }) asks for its own provider without
688+
* closing the panel that is already open.
689+
*/
690+
const openTabPanel = async (panel: vscode.WebviewPanel, forceNew = false): Promise<ClineProvider> => {
691+
vi.mocked(vscode.window.createWebviewPanel).mockReturnValueOnce(panel)
692+
const provider = await openClineInNewTab({
693+
context: mockContext,
694+
outputChannel: mockOutputChannel,
695+
webviewFocusTracker: mockProvider.webviewFocusTracker,
696+
forceNew,
697+
})
698+
// The automocked constructor does not run resolveWebviewView, so the view assignment
699+
// the real resolve makes (ClineProvider.ts:1896) has to be made here: the survivor rule
700+
// reads each instance's view, exactly as getInstanceForView does.
701+
provider["view"] = panel
702+
providersByView.set(panel, provider)
703+
return provider
704+
}
705+
706+
const viewStateCallback = (panel: vscode.WebviewPanel) =>
707+
(panel.onDidChangeViewState as Mock).mock.calls[0][0] as (event: { webviewPanel: vscode.WebviewPanel }) => void
708+
709+
const disposeCallback = (panel: vscode.WebviewPanel) => (panel.onDidDispose as Mock).mock.calls[0][0] as () => void
710+
711+
/**
712+
* Opens two live tab panels, re-points the tracker at the first one the way the
713+
* visibility handler does, and closes that tracked panel with its provider already
714+
* unregistered - the ordering the shipped wiring produces, because ClineProvider's own
715+
* view-dispose handler is registered inside resolveWebviewView (ClineProvider.ts:
716+
* 1907-1931), before the one in openClineInNewTab, so it runs first and clears the tab
717+
* ref. Each case states only the survivor's view state, which is what decides which
718+
* tier of the survivor rule it measures.
719+
*/
720+
const closeTrackedTabPanel = async (survivorPanel: vscode.WebviewPanel) => {
721+
const trackedPanel = makeTabPanel("closing-tab", { active: true, visible: true })
722+
await openTabPanel(trackedPanel)
723+
const survivorProvider = await openTabPanel(survivorPanel, true)
724+
viewStateCallback(trackedPanel)({ webviewPanel: trackedPanel })
725+
expect(getPanel()).toBe(trackedPanel)
726+
setPanel(undefined, "tab")
727+
providersByView.delete(trackedPanel)
728+
return { trackedPanel, survivorPanel, survivorProvider }
729+
}
730+
731+
it("keeps the live tab panel that is active tracked when the tracked panel closes", async () => {
732+
startInstanceRegistry()
733+
const survivorPanel = makeTabPanel("survivor-tab", { active: true, visible: true })
734+
const { trackedPanel, survivorProvider } = await closeTrackedTabPanel(survivorPanel)
735+
736+
disposeCallback(trackedPanel)()
737+
738+
// A sidebar is tracked as well, so "kept the survivor tracked" has to be proved
739+
// against the fallback: getPanel and focusInput must both name the tab.
740+
setPanel({} as vscode.WebviewView, "sidebar")
741+
expect(getPanel()).toBe(survivorPanel)
742+
743+
await handlers["zoo-code.focusInput"]()
744+
745+
expect(survivorProvider.postMessageToWebview).toHaveBeenCalledWith({
746+
type: "action",
747+
action: "focusInput",
748+
})
749+
expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
750+
})
751+
752+
it("tracks a visible but inactive survivor over the sidebar fallback", async () => {
753+
startInstanceRegistry()
754+
// The user closed the tab from a different group, so nothing reports itself active.
755+
const survivorPanel = makeTabPanel("survivor-tab", { active: false, visible: true })
756+
const { trackedPanel, survivorProvider } = await closeTrackedTabPanel(survivorPanel)
757+
758+
disposeCallback(trackedPanel)()
759+
760+
setPanel({} as vscode.WebviewView, "sidebar")
761+
expect(getPanel()).toBe(survivorPanel)
762+
await handlers["zoo-code.focusInput"]()
763+
expect(survivorProvider.postMessageToWebview).toHaveBeenCalledWith({
764+
type: "action",
765+
action: "focusInput",
766+
})
767+
expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
768+
})
769+
770+
it("tracks a survivor in a hidden group instead of dropping the tab surface", async () => {
771+
startInstanceRegistry()
772+
// A tab moved into a collapsed group is neither active nor visible, and it is still a
773+
// tab the user can click back to. Dropping the tracker here is the defect: the next
774+
// ordinary "Open in editor" builds a second panel beside it.
775+
const survivorPanel = makeTabPanel("survivor-tab", { active: false, visible: false })
776+
const { trackedPanel, survivorProvider } = await closeTrackedTabPanel(survivorPanel)
777+
778+
disposeCallback(trackedPanel)()
779+
780+
setPanel({} as vscode.WebviewView, "sidebar")
781+
expect(getPanel()).toBe(survivorPanel)
782+
await handlers["zoo-code.focusInput"]()
783+
expect(survivorProvider.postMessageToWebview).toHaveBeenCalledWith({
784+
type: "action",
785+
action: "focusInput",
786+
})
787+
expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
788+
})
789+
790+
it("opens into the surviving tab panel instead of creating a third one", async () => {
791+
startInstanceRegistry()
792+
const survivorPanel = makeTabPanel("survivor-tab", { active: true, visible: true })
793+
const { trackedPanel, survivorProvider } = await closeTrackedTabPanel(survivorPanel)
794+
const creationsBefore = vi.mocked(vscode.window.createWebviewPanel).mock.calls.length
795+
796+
disposeCallback(trackedPanel)()
797+
798+
const opened = await openClineInNewTab({
799+
context: mockContext,
800+
outputChannel: mockOutputChannel,
801+
webviewFocusTracker: mockProvider.webviewFocusTracker,
802+
})
803+
804+
// The reuse path is what keeps one panel per surface: it only fires while the tracker
805+
// names the live panel, so a cleared tracker must show up as a new creation.
806+
expect(vi.mocked(vscode.window.createWebviewPanel).mock.calls).toHaveLength(creationsBefore)
807+
expect(opened).toBe(survivorProvider)
808+
expect(survivorPanel.reveal).toHaveBeenCalled()
809+
expect(survivorProvider.postMessageToWebview).toHaveBeenCalledWith({
810+
type: "action",
811+
action: "didBecomeVisible",
812+
})
813+
})
814+
815+
it("selects the survivor when disposal arrives while the tracker still names the panel", async () => {
816+
startInstanceRegistry()
817+
const survivorPanel = makeTabPanel("survivor-tab", { active: true, visible: true })
818+
const trackedPanel = makeTabPanel("closing-tab", { active: true, visible: true })
819+
await openTabPanel(trackedPanel)
820+
await openTabPanel(survivorPanel, true)
821+
viewStateCallback(trackedPanel)({ webviewPanel: trackedPanel })
822+
// The other half of the state the stale-reference comment at registerCommands.ts:
823+
// 426-430 describes: the provider is gone while the tracker still points at the panel,
824+
// which is what a creation that failed after setPanel leaves behind. The branch that
825+
// owns this case must select the survivor rather than clear, and must not select the
826+
// panel being disposed - its registry entry is already gone.
827+
providersByView.delete(trackedPanel)
828+
829+
disposeCallback(trackedPanel)()
830+
831+
expect(getPanel()).toBe(survivorPanel)
832+
})
833+
834+
it("leaves the tab ref clear when the disposed panel was the last live tab", async () => {
835+
startInstanceRegistry()
836+
const lastPanel = makeTabPanel("last-tab", { active: true, visible: true })
837+
await openTabPanel(lastPanel)
838+
// Deliberately no onDidChangeViewState: that is the property that separates a panel
839+
// from a view, and ClineProvider itself uses it as the tab/sidebar discriminator
840+
// (ClineProvider.ts:1898). The describe's ClineProvider-typed double stands in for the
841+
// sidebar instance - only its view matters to the survivor rule.
842+
const sidebarView = {} as vscode.WebviewView
843+
const sidebarProvider = mockVisibleProviderInstance
844+
// The sidebar instance is live too, and its view is a WebviewView, not a panel: the
845+
// survivor rule must not put a sidebar view into the tab ref, because the tab branch of
846+
// focusInput would then post through the panel-shaped path at the wrong surface.
847+
sidebarProvider["view"] = sidebarView
848+
providersByView.set(sidebarView, sidebarProvider)
849+
// Provider-first ordering again: the ref is cleared and the instance unregistered
850+
// before registerCommands sees the disposal.
851+
setPanel(undefined, "tab")
852+
providersByView.delete(lastPanel)
853+
854+
disposeCallback(lastPanel)()
855+
856+
// Nothing is left in the tab surface, so the ref stays empty and the sidebar resumes.
857+
// This state already holds today; it is pinned so the survivor rule cannot break it by
858+
// pointing the tab ref at the panel that was just disposed.
859+
setPanel(sidebarView, "sidebar")
860+
expect(getPanel()).toBe(sidebarView)
861+
862+
await handlers["zoo-code.focusInput"]()
863+
864+
expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" })
865+
expect(lastPanel.reveal).not.toHaveBeenCalled()
866+
})
629867
// Coverage for the .catch arm on the sidebar title-bar post sites
630868
// (settingsButtonClicked posts twice, plus historyButtonClicked and
631869
// marketplaceButtonClicked) and acceptInput (the visible-provider path).
@@ -863,6 +1101,15 @@ describe("openClineInNewTab", () => {
8631101
setPanel(undefined, "tab")
8641102
})
8651103

1104+
// Same reset as the handlers block above: vi.clearAllMocks leaves implementations
1105+
// installed by a test in this block in place for the tests that follow it, and the
1106+
// survivor rule reads both lookups, so an instance left behind here would decide a
1107+
// later test that never registered it.
1108+
afterEach(() => {
1109+
;(ClineProvider.getInstanceForView as Mock).mockReset()
1110+
;(ClineProvider.getAllInstances as Mock).mockReset().mockReturnValue([])
1111+
})
1112+
8661113
it.each([false, true])(
8671114
"clears a closed tab reference only if it is still current (replacement: %s)",
8681115
async (replaced) => {
@@ -882,6 +1129,70 @@ describe("openClineInNewTab", () => {
8821129
},
8831130
)
8841131

1132+
it("leaves a live tab panel tracked when a failed creation clears the ref", async () => {
1133+
const survivorPanel = makeTabPanel("survivor-tab", { active: true, visible: true })
1134+
// View -> live instance, which is what the survivor rule reads through getAllInstances
1135+
// and getInstanceForView (ClineProvider.ts:1744-1756). The creation that fails below is
1136+
// deliberately absent from this map: its provider is disposed before the ref is
1137+
// cleared, and dispose unregisters the instance synchronously at its start
1138+
// (ClineProvider.ts:1653-1659), so the half-built panel cannot be picked.
1139+
const providerByView = new Map<vscode.WebviewPanel, ClineProvider>()
1140+
;(ClineProvider.getAllInstances as Mock).mockImplementation(() => [...providerByView.values()])
1141+
;(ClineProvider.getInstanceForView as Mock).mockImplementation((view: vscode.WebviewPanel) =>
1142+
providerByView.get(view),
1143+
)
1144+
vi.mocked(vscode.window.createWebviewPanel).mockReturnValueOnce(survivorPanel)
1145+
const survivorProvider = await openClineInNewTab({
1146+
context: mockContext,
1147+
outputChannel: mockOutputChannel,
1148+
webviewFocusTracker: new WebviewFocusTracker(),
1149+
})
1150+
// The resolve assigns the panel to the provider's own view (ClineProvider.ts:1896);
1151+
// the automocked constructor does not run it, so make the assignment here.
1152+
survivorProvider["view"] = survivorPanel
1153+
providerByView.set(survivorPanel, survivorProvider)
1154+
expect(getPanel()).toBe(survivorPanel)
1155+
1156+
// A forced call - startNewTask({ newTab: true }) - builds its own panel and makes it
1157+
// the tracked ref the moment it exists (registerCommands.ts:530). The failure lands
1158+
// after resolveWebviewView, at the visibility-listener registration, so the cleanup
1159+
// path is the one holding the ref.
1160+
// The panel double's registration hooks are read-only on the type, so the failing
1161+
// listener goes in through a fresh object literal rather than an assignment.
1162+
const failingPanel: vscode.WebviewPanel = {
1163+
...makeTabPanel("failing-tab", { active: true, visible: true }),
1164+
onDidChangeViewState: vi.fn(() => {
1165+
throw new Error("view state listener registration failed")
1166+
}),
1167+
}
1168+
vi.mocked(vscode.window.createWebviewPanel).mockReturnValueOnce(failingPanel)
1169+
1170+
await expect(
1171+
openClineInNewTab({
1172+
context: mockContext,
1173+
outputChannel: mockOutputChannel,
1174+
webviewFocusTracker: new WebviewFocusTracker(),
1175+
forceNew: true,
1176+
}),
1177+
).rejects.toThrow("view state listener registration failed")
1178+
1179+
// Same rule as onDidDispose: the ref goes to a live panel, not to nothing.
1180+
expect(getPanel()).toBe(survivorPanel)
1181+
expect(mockOutputChannel.appendLine).not.toHaveBeenCalledWith(expect.stringContaining("cleanup was incomplete"))
1182+
1183+
// The symptom a cleared ref produces: the next ordinary "Open in editor" reveals the
1184+
// panel that is still on screen instead of building a third one beside it.
1185+
const revealed = await openClineInNewTab({
1186+
context: mockContext,
1187+
outputChannel: mockOutputChannel,
1188+
webviewFocusTracker: new WebviewFocusTracker(),
1189+
})
1190+
expect(revealed).toBe(survivorProvider)
1191+
expect(survivorPanel.reveal).toHaveBeenCalledTimes(1)
1192+
// The survivor panel, then the failed one: no third panel was created.
1193+
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(2)
1194+
})
1195+
8851196
it("reuses a tab that appeared while the panel was being created", async () => {
8861197
const trackedPanel = {
8871198
reveal: vi.fn().mockResolvedValue(undefined),

0 commit comments

Comments
 (0)