Skip to content

Commit 76ab52f

Browse files
unit 3a: view state machinery, registration, and the boolean webview post
Part of the split plan issued on upstream issue 1992 for PR 2226. Content authority is PR 2226 head bc724b8, and every ported line is verbatim from that source at the same path, selected by donor new-side line range against unit 2's head cbf1114. Ranges here: ClineProvider.ts new-side 77 to 1149, 2419 to 2478 and 2537 to 2542; spec new- side 15 to 5270 plus the two postMessageToWebview mock reversions at 9667 and 9771; webviewMessageHandler.ts new-side 705 to 715 and its spec hunks at 131 to 132 and 2809 to 2826; src/__tests__/extension.spec.ts new-side 377; api-start-new-task.spec.ts new-side 22. The 2419 to 2478 and 2537 to 2542 groups and the two mock reversions at 377, 22, 9667 and 9771 came out of units 4 and 5 and travel here because 3a is the unit that ships Promise<boolean>: a mockResolvedValue(undefined) feeding that method, and the donor's rewritten diagnosticsRequest callback that returns it into a Promise<void) parameter, both fail typecheck at this head otherwise. 5 donor declarations moved to unit 3b, which owns their first use: - core/webview/ClineProvider.ts new-side 77: PROVIDER_SETTINGS_KEYS - core/webview/ClineProvider.ts new-side 177: PersistedViewStateValues - core/webview/ClineProvider.ts new-side 293: ViewLocalStateField - core/webview/__tests__/ClineProvider.spec.ts new-side 18: GlobalState - core/webview/ClineProvider.ts new-side 170: ViewLocalStateValues Each of those is an unused name at this head under @typescript-eslint/no-unused-vars, and the rule is the same one the plan already applies to assertions: a declaration ships with the unit whose code reads it. Unit 3b carries provider new-side 1150 onward and 6219 to 6398 and spec new-side 5723 to 6124, which is where every one of these is used. No changeset, no CHANGELOG edit, no suppression count change, no new file. The ViewStateRegistrationResult declaration and its doc comment (six lines, donor new-side 274 to 279) are not in this commit: their only reads are provider new-side 1153 and 1156, inside the 1150 to 1641 range unit 3b owns, so the declaration travels to the unit whose code reads it, the rule that also moved PROVIDER_SETTINGS_KEYS, ViewLocalStateValues, PersistedViewStateValues, ViewLocalStateField and GlobalState here. knip exits 0 at this head after the move. Main tip 18861b2 is merged into this commit as content: the tree is the ort merge of the cbf1114-parented content and main, merged clean with zero conflicts, so the merge base of this branch is main tip and the diff against main is this unit alone. The pure merge commit that produced this tree was 2b7e22ffa26d3b6f956a2e72301a400a85e5eb46 with parents d475ef2512d0e981f9b1a39c10d36a8729cdee71 and 18861b2; it was squashed into this one commit because the adaptation below can only compile once main's content is an ancestor of it, which the probe proved: main's copy of Task.spec.ts on top of the unmerged unit tree gives seven type errors, among them the missing module test-utils/run-state and four reads of Task.pendingPartialMessageTimer. One adapted line belongs to this commit's own signature change. src/core/task/__tests__/Task.spec.ts line 4526 adds return true inside the mockImplementation callback that main added at line 4521, because git show of ClineProvider.ts prints public async postMessageToWebview(message: ExtensionMessage) at line 1702 on main tip 18861b2 and the same line at 1702 on cbf1114, while this commit declares public async postMessageToWebview(message: ExtensionMessage): Promise<boolean> at line 2252. main brought the call site, this unit brought the boolean return, so the adaptation travels with the return type and not into the merge. It is a spec row, and the mutation gate charges executable paths, not spec rows.
1 parent 18861b2 commit 76ab52f

20 files changed

Lines changed: 892 additions & 36 deletions

‎packages/types/src/__tests__/global-settings.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,49 @@ describe("alwaysDenyUnapprovedCommands global setting", () => {
3939
})
4040
})
4141

42+
describe("viewStates global setting", () => {
43+
it("parses a valid per-view record", () => {
44+
const parsed = globalSettingsSchema.parse({
45+
viewStates: {
46+
"stable-view-1": { mode: "code", currentApiConfigName: "profile-a", updatedAt: 1730000000000 },
47+
"stable-view-2": {},
48+
},
49+
})
50+
expect(parsed.viewStates?.["stable-view-1"]).toEqual({
51+
mode: "code",
52+
currentApiConfigName: "profile-a",
53+
updatedAt: 1730000000000,
54+
})
55+
expect(parsed.viewStates?.["stable-view-2"]).toEqual({})
56+
expect(GLOBAL_SETTINGS_KEYS).toContain("viewStates")
57+
})
58+
59+
it("parses an entry that carries the host-minted claim token", () => {
60+
// The claim binds the entry to the webview that wrote it; a legacy entry without one
61+
// still parses, because refusing it is setViewStateId's job, not the schema's.
62+
const parsed = globalSettingsSchema.parse({
63+
viewStates: {
64+
"stable-view-1": { mode: "code", updatedAt: 1730000000000, claimToken: "7f9c-host-minted" },
65+
"stable-view-2": { mode: "code" },
66+
},
67+
})
68+
expect(parsed.viewStates?.["stable-view-1"]?.claimToken).toBe("7f9c-host-minted")
69+
expect(parsed.viewStates?.["stable-view-2"]).toEqual({ mode: "code" })
70+
})
71+
72+
it("rejects invalid field values inside a view entry", () => {
73+
expect(() => globalSettingsSchema.parse({ viewStates: { v: { mode: 42 } } })).toThrow()
74+
expect(() => globalSettingsSchema.parse({ viewStates: { v: { currentApiConfigName: 42 } } })).toThrow()
75+
expect(() => globalSettingsSchema.parse({ viewStates: { v: { updatedAt: "soon" } } })).toThrow()
76+
expect(() => globalSettingsSchema.parse({ viewStates: { v: { claimToken: 42 } } })).toThrow()
77+
})
78+
79+
it("rejects non-object viewStates values", () => {
80+
expect(() => globalSettingsSchema.parse({ viewStates: "not-a-record" })).toThrow()
81+
expect(() => globalSettingsSchema.parse({ viewStates: { v: "not-an-entry" } })).toThrow()
82+
})
83+
})
84+
4285
describe("collapseCommandOutputByDefault global setting", () => {
4386
it.each([true, false, undefined])("round-trips %s through the export/import schema", (value) => {
4487
const settings = globalSettingsSchema.parse({ collapseCommandOutputByDefault: value })

‎packages/types/src/__tests__/index.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
import { GLOBAL_STATE_KEYS } from "../index.js"
44

55
describe("GLOBAL_STATE_KEYS", () => {
6+
it("should contain registered durable per-view state", () => {
7+
expect(GLOBAL_STATE_KEYS).toContain("viewStates")
8+
})
9+
610
it("should contain provider settings keys", () => {
711
expect(GLOBAL_STATE_KEYS).toContain("autoApprovalEnabled")
812
})
@@ -13,6 +17,7 @@ describe("GLOBAL_STATE_KEYS", () => {
1317

1418
it("should not contain secret state keys", () => {
1519
expect(GLOBAL_STATE_KEYS).not.toContain("openRouterApiKey")
20+
expect(GLOBAL_STATE_KEYS).not.toContain("apiKey")
1621
})
1722

1823
it("should contain OpenAI Compatible base URL setting", () => {

‎packages/types/src/global-settings.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,17 @@ export const MAX_CHECKPOINT_TIMEOUT_SECONDS = 60
114114
*/
115115
export const DEFAULT_CHECKPOINT_TIMEOUT_SECONDS = 15
116116

117+
/**
118+
* Persisted non-secret selections for a stable webview instance.
119+
*/
120+
export const viewStateSchema = z.object({
121+
mode: z.string().optional(),
122+
currentApiConfigName: z.string().optional(),
123+
updatedAt: z.number().optional(),
124+
/** Host-minted token binding this entry to the webview that wrote it. */
125+
claimToken: z.string().optional(),
126+
})
127+
117128
/**
118129
* GlobalSettings
119130
*/
@@ -122,6 +133,7 @@ export const globalSettingsSchema = z.object({
122133
currentApiConfigName: z.string().optional(),
123134
listApiConfigMeta: z.array(providerSettingsEntrySchema).optional(),
124135
pinnedApiConfigs: z.record(z.string(), z.boolean()).optional(),
136+
viewStates: z.record(z.string(), viewStateSchema).optional(),
125137

126138
lastShownAnnouncementId: z.string().optional(),
127139
customInstructions: z.string().optional(),

‎packages/types/src/vscode-extension-host.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ export interface ExtensionMessage {
113113
| "rooHistoryImportProgress"
114114
| "themeFixtureProbeRequest"
115115
| "diagnosticsRequest"
116+
| "viewStateClaim"
116117
text?: string
117118
/** For fileContent: { path, content, error? } */
118119
fileContent?: { path: string; content: string | null; error?: string }
@@ -171,6 +172,13 @@ export interface ExtensionMessage {
171172
// eslint-disable-next-line @typescript-eslint/no-explicit-any
172173
values?: Record<string, any>
173174
requestId?: string
175+
/**
176+
* For `viewStateClaim`: the durable `viewStates` key the delivered claim governs. The
177+
* message is only ever sent to the webview that key belongs to.
178+
*/
179+
viewStateId?: string
180+
/** For `viewStateClaim`: the host-minted token the webview stores and echoes on launch. */
181+
viewStateClaim?: string
174182
themeFixture?: WebviewThemeFixture
175183
diagnostics?: WebviewDiagnosticsSnapshot
176184
promptText?: string
@@ -712,6 +720,9 @@ export interface WebviewMessage {
712720
| "themeFixtureProbeResponse"
713721
| "diagnosticsResponse"
714722
text?: string
723+
viewStateId?: string
724+
/** For `webviewDidLaunch`: the claim delivered for `viewStateId`, enforced by setViewStateId. */
725+
viewStateClaim?: string
715726
taskId?: string
716727
editedMessageContent?: string
717728
tab?: "settings" | "history" | "mcp" | "modes" | "chat" | "marketplace" | "cloud"

‎src/__tests__/extension.spec.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ describe("extension.ts", () => {
374374
const getAll = vi.mocked(ClineProvider.getAllInstances)
375375
const post = vi.mocked(provider.postMessageToWebview)
376376
getAll.mockReturnValue([provider, provider])
377-
post.mockRejectedValueOnce(new Error("delivery failed")).mockResolvedValue(undefined)
377+
post.mockRejectedValueOnce(new Error("delivery failed")).mockResolvedValue(true)
378378
try {
379379
const { activate } = await import("../extension")
380380
await activate(mockContext)

‎src/core/config/ContextProxy.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,21 @@ const globalSettingsExportSchema = globalSettingsSchema.omit({
6767
taskHistory: true,
6868
listApiConfigMeta: true,
6969
currentApiConfigName: true,
70+
// Host-minted claim tokens and per-view selections are not user-settings: exporting
71+
// them would let a settings file be replayed as another view's identity.
72+
viewStates: true,
7073
})
7174

75+
/**
76+
* Global settings a settings file may not carry in either direction. Per-view selections and the
77+
* claim token that binds them are minted and held by the extension host, so a file that could
78+
* set them would be replayable as another view's identity. The export side omits the key above;
79+
* the import side consults this list in `sanitizeGlobalSettings`.
80+
*/
81+
const NON_PORTABLE_SETTINGS_KEYS: readonly string[] = ["viewStates"]
82+
83+
export const isNonPortableSettingsKey = (key: string): boolean => NON_PORTABLE_SETTINGS_KEYS.includes(key)
84+
7285
export class ContextProxy {
7386
private readonly originalContext: vscode.ExtensionContext
7487

@@ -666,7 +679,16 @@ export class ContextProxy {
666679
* rollback, must provide it themselves.
667680
*/
668681
public async setValues(values: RooCodeSettings) {
669-
const entries = Object.entries(values) as [RooCodeSettingsKey, unknown][]
682+
// viewStates is host-owned: per-view selections and the claim token that binds them are
683+
// minted by the extension host, so no configuration path may carry them. Every caller of
684+
// this setter takes input that did not originate inside the host - a posted updateSettings,
685+
// a newTask taskConfiguration, the external API, an imported settings file - so the filter
686+
// lives here rather than at whichever caller a reviewer happened to point at. The host's
687+
// own view-state methods write through setValue("viewStates", ...), which stays open.
688+
const entries = Object.entries(values).filter(([key]) => !isNonPortableSettingsKey(key)) as [
689+
RooCodeSettingsKey,
690+
unknown,
691+
][]
670692
const results = await Promise.allSettled(entries.map(([key, value]) => this.setValue(key, value)))
671693

672694
const committed: string[] = []

‎src/core/config/ProviderSettingsManager.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ export const providerProfilesSchema = z.object({
5555

5656
export type ProviderProfiles = z.infer<typeof providerProfilesSchema>
5757

58+
/** Already-deleted profile: callers branch on this type instead of matching message text. */
59+
export class ProviderSettingsNotFoundError extends Error {
60+
constructor(message: string) {
61+
super(message)
62+
this.name = "ProviderSettingsNotFoundError"
63+
}
64+
}
65+
5866
export class ProviderSettingsManager {
5967
private static readonly SCOPE_PREFIX = "roo_cline_config_"
6068
private readonly defaultConfigId = this.generateId()
@@ -511,7 +519,7 @@ export class ProviderSettingsManager {
511519
const providerProfiles = await this.load()
512520

513521
if (!providerProfiles.apiConfigs[name]) {
514-
throw new Error(`Config '${name}' not found`)
522+
throw new ProviderSettingsNotFoundError(`Config '${name}' not found`)
515523
}
516524

517525
if (Object.keys(providerProfiles.apiConfigs).length === 1) {
@@ -522,6 +530,11 @@ export class ProviderSettingsManager {
522530
await this.store(providerProfiles)
523531
})
524532
} catch (error) {
533+
// A missing config is a caller-meaningful signal, not a failure: rethrow it
534+
// unwrapped so callers can branch on the type instead of message text.
535+
if (error instanceof ProviderSettingsNotFoundError) {
536+
throw error
537+
}
525538
throw new Error(`Failed to delete config: ${error}`)
526539
}
527540
}

‎src/core/config/__tests__/ContextProxy.spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,25 @@ describe("ContextProxy", () => {
837837
})
838838
})
839839

840+
describe("export()", () => {
841+
it("omits host-owned viewStates from a settings export", async () => {
842+
await proxy.setValue("viewStates", {
843+
"export-view": { claimToken: "export-claim-token", mode: "architect" },
844+
})
845+
// A portable global setting the export schema keeps: without it the test would pass on an
846+
// empty export, because every remaining check only asserts absence.
847+
await proxy.setValue("customInstructions", "retain these instructions")
848+
// The cache carries the key; only the export must not.
849+
expect(Object.keys(proxy.getValues())).toContain("viewStates")
850+
const exported = await proxy.export()
851+
expect(exported?.customInstructions).toBe("retain these instructions")
852+
expect(exported && Object.keys(exported)).not.toContain("viewStates")
853+
expect(exported && "viewStates" in exported).toBe(false)
854+
// The value must not escape under another name either: the claim token is host state.
855+
expect(JSON.stringify(exported)).not.toContain("export-claim-token")
856+
})
857+
})
858+
840859
describe("resetAllState", () => {
841860
it("should clear all in-memory caches", async () => {
842861
// Setup initial state in caches

‎src/core/config/__tests__/ProviderSettingsManager.spec.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
import { clearAllMocks } from "../../../test-utils/reset"
1313
import { makeExtensionContext } from "../../../test-utils/vscode"
1414

15-
import { ProviderSettingsManager, ProviderProfiles } from "../ProviderSettingsManager"
15+
import { ProviderSettingsManager, ProviderSettingsNotFoundError, ProviderProfiles } from "../ProviderSettingsManager"
1616

1717
// `export()` builds an API handler per profile to read model capabilities. Mock
1818
// buildApiHandler with the real @roo-code/types model definitions so the token-field
@@ -973,6 +973,11 @@ describe("ProviderSettingsManager", () => {
973973
}),
974974
)
975975

976+
// The typed not-found signal is the contract callers branch on: a profile
977+
// name containing "not found" must not be matchable via message text.
978+
await expect(providerSettingsManager.deleteConfig("nonexistent")).rejects.toBeInstanceOf(
979+
ProviderSettingsNotFoundError,
980+
)
976981
await expect(providerSettingsManager.deleteConfig("nonexistent")).rejects.toThrow(
977982
"Config 'nonexistent' not found",
978983
)

‎src/core/config/__tests__/importExport.spec.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,55 @@ describe("importExport", () => {
251251
})
252252
})
253253

254+
describe("host-owned view state on import", () => {
255+
const settingsWithImportedViewStates = JSON.stringify({
256+
providerProfiles: {
257+
currentApiConfigName: "test",
258+
apiConfigs: {
259+
test: { apiProvider: providerIdentifiers.openai, apiKey: "test-key", id: "test-id" },
260+
},
261+
},
262+
globalSettings: {
263+
customInstructions: "keep me",
264+
viewStates: { "view-1": { mode: "architect", claimToken: "planted-claim" } },
265+
},
266+
})
267+
268+
beforeEach(() => {
269+
;(fs.readFile as Mock).mockResolvedValue(settingsWithImportedViewStates)
270+
mockProviderSettingsManager.export.mockResolvedValue({
271+
currentApiConfigName: "default",
272+
apiConfigs: { default: { apiProvider: providerIdentifiers.anthropic, id: "default-id" } },
273+
})
274+
mockProviderSettingsManager.import.mockResolvedValue(undefined)
275+
mockProviderSettingsManager.listConfig.mockResolvedValue([])
276+
mockContextProxy.setValues.mockResolvedValue(undefined)
277+
mockContextProxy.setValue.mockResolvedValue(undefined)
278+
mockContextProxy.setProviderSettings.mockResolvedValue(undefined)
279+
})
280+
281+
it("drops viewStates so an imported file cannot plant another view's claim", async () => {
282+
const result = await importSettingsFromPath("/mock/path/settings.json", {
283+
providerSettingsManager: mockProviderSettingsManager,
284+
contextProxy: mockContextProxy,
285+
customModesManager: mockCustomModesManager,
286+
})
287+
288+
expect(result).toMatchObject({ success: true })
289+
290+
// A claim token is host-minted: a file that could carry an entry could replay it as that
291+
// view's identity, so the key is dropped before anything is written.
292+
expect(mockContextProxy.setValues).toHaveBeenCalledTimes(1)
293+
const [appliedSettings] = (mockContextProxy.setValues as Mock).mock.calls[0]
294+
expect(appliedSettings).not.toHaveProperty("viewStates")
295+
expect(appliedSettings).toMatchObject({ customInstructions: "keep me" })
296+
const warnings = (result as { warnings?: string[] }).warnings ?? []
297+
expect(warnings).toHaveLength(1)
298+
expect(warnings[0]).toContain('globalSettings.viewStates" was skipped')
299+
expect(warnings[0]).toContain("not portable")
300+
})
301+
})
302+
254303
describe("importSettings", () => {
255304
it("should return success: false when user cancels file selection", async () => {
256305
;(vscode.window.showOpenDialog as Mock).mockResolvedValue(undefined)

0 commit comments

Comments
 (0)