Skip to content

Commit 050b5f0

Browse files
fix(commands): answer the ten human review rows on the panel seam
Three of the ten rows were live defects, seven were coverage gaps that could pass with the behaviour removed. - registerCommands.ts: a failed first resolveWebviewView left the blank panel open and still tracked: setPanel runs before the resolve and the panel's own onDidDispose is only registered after it, so nothing else could clear the ref. The catch clears the identity-checked ref, disposes the panel and rethrows. - commandManifest.spec.ts: new suite reading the contributes manifest; pins the four *InTab ids, their editor/title and commandPalette gates, the sidebar view/title gates and the i18n placeholder titles. - registerCommands.spec.ts: sidebar lookup stubs are view-specific and the sidebar provider is a distinct double, so a fallback to the sidebar fails instead of passing; pins the arguments handed to focusPanel and the reveal-then-post invocation order; adds the failed-resolve control test. - ClineProvider.spec.ts: asserts through the registerCommands seam that a replacement view is tracked, that a late disposal of the replaced view does not clear it, and that disposing the sidebar view releases the ref; both disposal loops assert a non-empty listener list before looping. - ClineProvider.ts: setWebviewMessageListener JSDoc named a parameter that no longer exists and stayed silent about the view identity guard. - registerCommands.ts: the CommandCallback comment still explained an any[] rest that commit 2860e2b had already narrowed to never[]. Co-authored-by: easonLiangWorldedtech <[email protected]>
1 parent b0946f1 commit 050b5f0

5 files changed

Lines changed: 192 additions & 17 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import fs from "fs"
2+
import { fileURLToPath } from "url"
3+
4+
import { describe, expect, it } from "vitest"
5+
6+
// This suite reads the contributes manifest itself rather than a constant copied from it: the
7+
// command ids, the menu rows and the `when` clauses below are what decide whether a title-bar
8+
// button reaches the handler that owns it, and nothing else in the repo checks them. Renaming an
9+
// id, flipping a clause or dropping a row is invisible to every other test in the suite.
10+
const manifest = JSON.parse(fs.readFileSync(fileURLToPath(new URL("../../package.json", import.meta.url)), "utf8"))
11+
const commands: { command: string; title: string }[] = manifest.contributes.commands
12+
const menus = manifest.contributes.menus as Record<string, { command: string; when?: string }[]>
13+
14+
const TAB_PANEL_ID = "zoo-code.TabPanelProvider"
15+
const SIDEBAR_VIEW_CLAUSE = `view == zoo-code.SidebarProvider`
16+
const TAB_ACTIVE_CLAUSE = `activeWebviewPanelId == ${TAB_PANEL_ID}`
17+
const TAB_INACTIVE_CLAUSE = `activeWebviewPanelId != ${TAB_PANEL_ID}`
18+
19+
const declared = new Set(commands.map((c) => c.command))
20+
const titleBarCommands = [...new Set([...menus["editor/title"], ...menus["view/title"]].map((r) => r.command))]
21+
const tabTitleCommands = titleBarCommands.filter((id) => id.endsWith("InTab"))
22+
const sidebarTitleCommands = titleBarCommands.filter((id) => !id.endsWith("InTab"))
23+
24+
// popoutButtonClicked is a view/title-only affordance: it has no commandPalette row.
25+
const sidebarTaskCommands = sidebarTitleCommands.filter((id) => !id.endsWith("popoutButtonClicked"))
26+
describe("contributes manifest for the title-bar commands", () => {
27+
it("declares every command the menus reference", () => {
28+
for (const id of titleBarCommands) {
29+
expect(declared, `${id} is used in a menu but not declared in contributes.commands`).toContain(id)
30+
}
31+
})
32+
33+
it.each(tabTitleCommands)("%s has an editor/title row gated on the tab panel", (id) => {
34+
const row = menus["editor/title"].find((r) => r.command === id)
35+
expect(row, `${id} must appear in editor/title`).toBeDefined()
36+
expect(row.when, `${id} must be gated on the active tab panel`).toBe(TAB_ACTIVE_CLAUSE)
37+
})
38+
39+
it.each(tabTitleCommands)("%s has a commandPalette row gated on the tab panel", (id) => {
40+
const row = menus.commandPalette.find((r) => r.command === id)
41+
expect(row, `${id} must appear in commandPalette`).toBeDefined()
42+
expect(row.when, `${id} must be gated on the active tab panel`).toBe(TAB_ACTIVE_CLAUSE)
43+
})
44+
45+
it.each(sidebarTitleCommands)("%s has a view/title row gated on the sidebar view", (id) => {
46+
const row = menus["view/title"].find((r) => r.command === id)
47+
expect(row, `${id} must appear in view/title`).toBeDefined()
48+
expect(row.when, `${id} must be gated on the sidebar view`).toBe(SIDEBAR_VIEW_CLAUSE)
49+
})
50+
51+
// popoutButtonClicked is a view/title-only row: it has no commandPalette entry, and the four
52+
// sidebar task commands each have one hidden while the tab panel is the active webview.
53+
it.each(sidebarTaskCommands)("%s has a commandPalette row hidden while the tab panel is active", (id) => {
54+
const row = menus.commandPalette.find((r) => r.command === id)
55+
expect(row, `${id} must appear in commandPalette`).toBeDefined()
56+
expect(row.when, `${id} must be hidden while the tab panel is the active webview`).toBe(TAB_INACTIVE_CLAUSE)
57+
})
58+
it("keeps popoutButtonClicked out of the command palette", () => {
59+
// It is a title-bar affordance only: giving it a palette row would expose a command that
60+
// needs an active webview to mean anything.
61+
expect(
62+
menus.commandPalette.map((r) => r.command),
63+
"popout belongs in view/title only",
64+
).not.toContain("zoo-code.popoutButtonClicked")
65+
})
66+
67+
it("surfaces the failure message when a menu references an undeclared id", () => {
68+
// The per-id rows above carry a failure message built from the id. This row proves the message
69+
// reaches the reporter: without it a renamed command id would fail with an empty diff.
70+
const id = "zoo-code.notDeclaredInCommands"
71+
const message = id + " is used in a menu but not declared in contributes.commands"
72+
expect(() => {
73+
expect(id, message).toBe("zoo-code.declaredElsewhere")
74+
}, message).toThrowError(message)
75+
})
76+
it("names the title-bar commands with i18n placeholders, not literals", () => {
77+
for (const id of titleBarCommands) {
78+
const entry = commands.find((c) => c.command === id)
79+
expect(entry, `${id} must be declared`).toBeDefined()
80+
expect(entry.title, `${id} must carry a %placeholder title`).toMatch(/^%/)
81+
}
82+
})
83+
})

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

Lines changed: 68 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -530,11 +530,15 @@ describe("registerCommands handlers", () => {
530530
})
531531
})
532532

533-
it("focusInput awaits postMessage on the registered provider when a sidebar panel is active", async () => {
533+
it("focusInput awaits postMessage on the instance resolved from the tracked sidebar view", async () => {
534534
const fakeSidebar = {} as vscode.WebviewView
535535
setPanel(fakeSidebar, "sidebar")
536-
// The sidebar target is resolved through the live-instance lookup.
537-
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockProvider)
536+
// The sidebar target is resolved through the live-instance lookup, so the lookup has to hand back
537+
// a provider that is NOT the one registered at activation: if both names refer to the same
538+
// double, a handler that posted to the registered provider instead of the looked-up instance
539+
// would pass either way.
540+
const sidebarProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) }
541+
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(sidebarProvider)
538542

539543
// Same deferred-promise pattern as above. focusInput first awaits
540544
// focusPanel() (mocked to resolve sync) and then awaits
@@ -545,7 +549,7 @@ describe("registerCommands handlers", () => {
545549
const postPromise = new Promise<void>((resolve) => {
546550
resolvePost = resolve
547551
})
548-
mockProvider.postMessageToWebview.mockReturnValueOnce(postPromise)
552+
sidebarProvider.postMessageToWebview.mockReturnValueOnce(postPromise)
549553

550554
const handlerPromise = handlers["zoo-code.focusInput"]() as Promise<unknown>
551555
let settled = false
@@ -559,10 +563,13 @@ describe("registerCommands handlers", () => {
559563
resolvePost()
560564
await handlerPromise
561565

562-
expect(mockProvider.postMessageToWebview).toHaveBeenCalledWith({
566+
expect(ClineProvider.getInstanceForView as Mock).toHaveBeenCalledWith(fakeSidebar)
567+
expect(sidebarProvider.postMessageToWebview).toHaveBeenCalledWith({
563568
type: "action",
564569
action: "focusInput",
565570
})
571+
// The registered provider is a different double: it must not receive the post.
572+
expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
566573
})
567574

568575
it("focusInput does not post when no sidebar panel is tracked", async () => {
@@ -575,7 +582,8 @@ describe("registerCommands handlers", () => {
575582
})
576583

577584
it("focusInput posts to the tab provider when a tab panel is tracked alongside the sidebar", async () => {
578-
setPanel({} as vscode.WebviewView, "sidebar")
585+
const sidebarView = {} as vscode.WebviewView
586+
setPanel(sidebarView, "sidebar")
579587
const tabPanel = {} as vscode.WebviewPanel
580588
setPanel(tabPanel, "tab")
581589
const tabProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) }
@@ -585,6 +593,9 @@ describe("registerCommands handlers", () => {
585593

586594
// focusPanel selects the tab when one is tracked, so the focus message follows that
587595
// selection: the tab webview is the one that became visible and must receive it.
596+
// Pin the arguments handed to focusPanel, not only the outcome: swapping them would make
597+
// focusPanel reveal the sidebar while the post still followed the tracked tab.
598+
expect(focusPanel).toHaveBeenCalledWith(tabPanel, sidebarView)
588599
expect(ClineProvider.getInstanceForView as Mock).toHaveBeenCalledWith(tabPanel)
589600
expect(tabProvider.postMessageToWebview).toHaveBeenCalledWith({ type: "action", action: "focusInput" })
590601
expect(mockProvider.postMessageToWebview).not.toHaveBeenCalled()
@@ -596,10 +607,16 @@ describe("registerCommands handlers", () => {
596607
// that lookup finds no live instance (tab provider disposed or untracked), the
597608
// sidebar must not receive the post - focusPanel made the tab visible, so a
598609
// sidebar post would focus an input the user cannot see.
599-
setPanel({} as vscode.WebviewView, "sidebar")
610+
const sidebarView = {} as vscode.WebviewView
611+
setPanel(sidebarView, "sidebar")
600612
const tabPanel = {} as vscode.WebviewPanel
601613
setPanel(tabPanel, "tab")
602-
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined)
614+
// The lookup is view-specific on purpose: the tab lookup must miss while the sidebar stays live.
615+
// A blanket `undefined` cannot tell "no fallback" apart from "fell back to a sidebar that also
616+
// resolved to nothing", which is the defect these silence assertions exist to catch.
617+
;(ClineProvider.getInstanceForView as Mock).mockImplementation((view: unknown) =>
618+
view === tabPanel ? undefined : mockProvider,
619+
)
603620

604621
await handlers["zoo-code.focusInput"]()
605622

@@ -949,11 +966,12 @@ describe("openClineInNewTab", () => {
949966

950967
it("reveals the existing tab instead of creating a second panel", async () => {
951968
const mockExistingProvider = { postMessageToWebview: vi.fn().mockResolvedValue(undefined) }
969+
const revealMock = vi.fn().mockResolvedValue(undefined)
952970
const mockPanel = {
953971
webview: { postMessage: vi.fn() },
954972
onDidChangeViewState: vi.fn(),
955973
onDidDispose: vi.fn(),
956-
reveal: vi.fn().mockResolvedValue(undefined),
974+
reveal: revealMock,
957975
} as unknown as vscode.WebviewPanel
958976
setPanel(mockPanel, "tab")
959977
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(mockExistingProvider)
@@ -965,12 +983,18 @@ describe("openClineInNewTab", () => {
965983
})
966984

967985
expect(result).toBe(mockExistingProvider)
968-
expect(mockPanel.reveal).toHaveBeenCalledTimes(1)
986+
expect(revealMock).toHaveBeenCalledTimes(1)
969987
expect(vscode.window.createWebviewPanel).not.toHaveBeenCalled()
970988
expect(mockExistingProvider.postMessageToWebview).toHaveBeenCalledWith({
971989
type: "action",
972990
action: "didBecomeVisible",
973991
})
992+
// Each assertion above is order-blind on its own. The contract is reveal first, then the
993+
// didBecomeVisible post: posting first would light up an input in a panel the user cannot
994+
// see yet, so the invocation order is pinned directly.
995+
expect(revealMock.mock.invocationCallOrder[0]).toBeLessThan(
996+
mockExistingProvider.postMessageToWebview.mock.invocationCallOrder[0],
997+
)
974998
})
975999

9761000
it("creates a new tab panel when the tracked tab's provider has been disposed", async () => {
@@ -993,6 +1017,40 @@ describe("openClineInNewTab", () => {
9931017
expect(vscode.window.createWebviewPanel).toHaveBeenCalledTimes(1)
9941018
})
9951019

1020+
it("disposes the new panel and clears the tab ref when the first resolve rejects", async () => {
1021+
// The tab ref is stored before the resolve and the panel's own disposal handler is registered
1022+
// only after it, so a failed resolve used to leave a blank panel open and tracked: the next
1023+
// click would reveal a panel whose webview never resolved.
1024+
const failedPanel = {
1025+
webview: { postMessage: vi.fn() },
1026+
onDidChangeViewState: vi.fn(),
1027+
onDidDispose: vi.fn(),
1028+
dispose: vi.fn(),
1029+
reveal: vi.fn().mockResolvedValue(undefined),
1030+
} as unknown as vscode.WebviewPanel
1031+
;(vscode.window.createWebviewPanel as Mock).mockReturnValue(failedPanel)
1032+
;(ClineProvider.getInstanceForView as Mock).mockReturnValue(undefined)
1033+
const ctor = ClineProvider as unknown as Mock
1034+
// A regular function, not an arrow: the class mock is constructed with new, and an arrow factory
1035+
// throws "is not a constructor". Once, so it is consumed by this test only.
1036+
ctor.mockImplementationOnce(function (this: unknown) {
1037+
return {
1038+
resolveWebviewView: vi.fn().mockRejectedValue(new Error("webview resolve failed")),
1039+
} as unknown as ClineProvider
1040+
})
1041+
1042+
await expect(
1043+
openClineInNewTab({
1044+
context: mockContext,
1045+
outputChannel: mockOutputChannel,
1046+
webviewFocusTracker: tabFocusTracker,
1047+
}),
1048+
).rejects.toThrow("webview resolve failed")
1049+
1050+
expect(failedPanel.dispose).toHaveBeenCalledTimes(1)
1051+
expect(getPanel()).toBeUndefined()
1052+
})
1053+
9961054
it("falls back to an undefined MdmService when MdmService.getInstance throws", async () => {
9971055
;(MdmService.getInstance as Mock).mockImplementation(() => {
9981056
throw new Error("MDM service not initialized")

‎src/activate/registerCommands.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,14 @@ export const registerCommands = (options: RegisterCommandOptions) => {
114114
// excluded from this map.
115115
//
116116
// Callback shape mirrors VS Code's own `commands.registerCommand` signature
117-
// (`(...args: any[]) => any`), with the return narrowed to `unknown` so
118-
// callers must inspect before using. `any[]` for args is unavoidable: the
119-
// callbacks here are heterogeneous (`importSettings` takes an optional
120-
// `filePath?: string`, others take none) and VS Code dispatches positional
121-
// args dynamically.
117+
// (`(...args: any[]) => any`) except for the args, which are typed `never[]`.
118+
// Nothing in this file calls these callbacks - VS Code dispatches positional
119+
// args dynamically - so `never[]` is the stricter choice: it accepts every
120+
// callback shape in the map (`importSettings` takes an optional
121+
// `filePath?: string`, the rest take none) while a direct call like
122+
// `cb("path")` fails to typecheck instead of compiling silently. Widening the
123+
// rest back to `any[]` would drop that guard. The return stays narrowed to
124+
// `unknown` so callers must inspect before using.
122125
type CommandCallback = (...args: never[]) => unknown
123126

124127
// Posts each action in order to the target instance. Failures are logged
@@ -460,7 +463,17 @@ const createTabPanelUnlocked = async ({ context, outputChannel, webviewFocusTrac
460463
dark: vscode.Uri.joinPath(context.extensionUri, "assets", "icons", "panel_dark.png"),
461464
}
462465

463-
await tabProvider.resolveWebviewView(newPanel)
466+
try {
467+
await tabProvider.resolveWebviewView(newPanel)
468+
} catch (error) {
469+
// The tab ref is already this panel (setPanel above) and the panel's own disposal handler is
470+
// only registered below, so a failed resolve has to close the blank panel and clear the ref
471+
// itself before rethrowing: otherwise the next click reveals a panel whose webview never
472+
// resolved, and the tracked ref keeps pointing at it.
473+
if (tabPanel === newPanel) setPanel(undefined, "tab")
474+
newPanel.dispose()
475+
throw error
476+
}
464477

465478
// Add listener for visibility changes to notify webview
466479
newPanel.onDidChangeViewState(

‎src/core/webview/ClineProvider.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1983,7 +1983,10 @@ export class ClineProvider
19831983
* Sets up an event listener to listen for messages passed from the webview context and
19841984
* executes code based on the message that is received.
19851985
*
1986-
* @param webviewView The view whose webview messages are listened to
1986+
* @param webview The webview whose messages are listened to
1987+
* @param view The view that owns `webview`. The listener drops every message whose view is no
1988+
* longer the provider's current view, so a late message from a replaced view cannot act on the
1989+
* replacement's state.
19871990
*/
19881991
private setWebviewMessageListener(webview: vscode.Webview, view: vscode.WebviewView | vscode.WebviewPanel) {
19891992
const onReceiveMessage = async (message: WebviewMessage) => {

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../../api/pr
4141
import { makeCompositeDisposable, makeEventEmitter } from "../../../test-utils/vscode"
4242
import { WebviewFocusTracker } from "../WebviewFocusTracker"
4343
import { resolveChatProvider } from "../../../activate/resolveChatProvider"
44+
import { getPanel, setPanel } from "../../../activate/registerCommands"
4445

4546
// Mock setup must come before imports.
4647
vi.mock("../../prompts/sections/custom-instructions")
@@ -647,17 +648,25 @@ describe("ClineProvider", () => {
647648

648649
await provider.resolveWebviewView(first.view)
649650
// The replacement resolves before the old view's disposal callback runs.
651+
// (and before the tracked sidebar ref is consulted by the late disposal below).
650652
await provider.resolveWebviewView(second.view)
651653

654+
expect(getPanel(), "the replacement view must be the tracked sidebar").toBe(second.view)
655+
652656
await first.triggerDispose()
653657

654658
// Cleanup is scoped to the surface that went away: the replacement keeps every listener.
655659
for (const disposable of second.disposables) {
656660
expect(disposable.dispose).not.toHaveBeenCalled()
657661
}
662+
expect(second.disposables.length, "the replacement view must have listeners at stake").toBeGreaterThan(0)
663+
expect(first.disposables.length, "the disposed view must have had listeners to release").toBeGreaterThan(0)
658664
for (const disposable of first.disposables) {
659665
expect(disposable.dispose).toHaveBeenCalled()
660666
}
667+
// The disposal below is identity-checked: a late disposal of the view that was already
668+
// replaced must not clear the ref, or the commands and this provider would lose the live view.
669+
expect(getPanel(), "a late disposal of the replaced view must not clear the tracked ref").toBe(second.view)
661670
await provider.dispose()
662671
})
663672

@@ -698,6 +707,9 @@ describe("ClineProvider", () => {
698707
const configDisposable = { dispose: vi.fn() }
699708
vi.mocked(vscode.workspace.onDidChangeConfiguration).mockReturnValue(configDisposable)
700709

710+
// Tracked explicitly rather than relying on the resolve-time bookkeeping, so the assertion
711+
// below cannot pass on state some earlier test left behind.
712+
setPanel(view, "sidebar")
701713
await provider.resolveWebviewView(view)
702714

703715
// Registering the view puts its listeners in the provider's one disposable list.
@@ -715,6 +727,12 @@ describe("ClineProvider", () => {
715727
await callback()
716728
}
717729

730+
// The tracked sidebar ref is gone too: ClineProvider and the sidebar commands read it through
731+
// the registerCommands seam, and a disposed view left behind there would be handed to
732+
// focusPanel and to every title-bar command as if it were still on screen. Deleting the
733+
// clearSidebarPanel call in the sidebar disposal branch fails here.
734+
expect(getPanel(), "the disposed sidebar view must no longer be tracked").toBeUndefined()
735+
718736
// The one drain is what releases them: every registration the view caused - message listener,
719737
// focus registration, visibility listener, configuration listener - is gone from the list, and none
720738
// of them survives as something a later owner would have to clean up.

0 commit comments

Comments
 (0)