Skip to content

fix(webview): invalidate live sibling view state on reset and settings import (vps2 F4) - #1562

Open
easonLiangWorldedtech wants to merge 24 commits into
Zoo-Code-Org:mainfrom
easonLiangWorldedtech:vps2/f4-cross-instance-reset
Open

easonLiangWorldedtech wants to merge 24 commits into
Zoo-Code-Org:mainfrom
easonLiangWorldedtech:vps2/f4-cross-instance-reset

Conversation

@easonLiangWorldedtech

Copy link
Copy Markdown
Contributor

Draft PR — vps2 unit F4 (cross-instance reset + import invalidation).

Tracking: easonLiangWorldedtech#41 (vps2 series ledger). Upstream issue: #1561 (this series' gap record; the original upstream bug is #980). Port source: upstream PR #981 (fix(webview): invalidate per-view state after reset and import) — closed draft, superseded by the vps2 series; the #41 ledger names #981 as the F4 port source.

Scope

5 files, 342 insertions, 1 deletion (measured vs stack base 8da5c6e):

  • src/core/webview/ClineProvider.ts (21+/0−) — the broadcastResetToAllInstances() method: every live instance clears its in-memory view-local state (_clearViewLocalState), the global contextProxy.setValue("viewStates", undefined) write clears the durable per-view entries in a single write-queue clear, and each non-calling instance re-posts its state to its webview. Wired into resetState (comment + await this.broadcastResetToAllInstances()) before its final postStateToWebview().
  • src/core/config/importExport.ts (13+/0−) — ImportWithProviderOptions gains the optional broadcastResetToAllInstances(): Promise; importSettingsWithFeedback gains the guarded broadcast block after the settingsImportedAt write (try/catch: a broadcast failure is console.warn'd and never fails the import).
  • src/core/config/tests/importExport.spec.ts (158+/0−) — the 3 fix(webview): invalidate per-view state after reset and import #981 tests (broadcast on successful import; skip when the callback is missing — with a gate-required console.warn negative assertion pinning the guarded call; import result kept successful when the broadcast throws — console.warn spied and restored); the raw provider-identifier casts of the fix(webview): invalidate per-view state after reset and import #981 text are adapted to the providerIdentifiers.* constants (lint-required, no semantic change).
  • src/core/webview/tests/ClineProvider.parallelMode.spec.ts (116+/0−) — the F4 multi-instance + _clearViewLocalState describes appended from the CS copy (116 lines: CS L1674-L1789, byte-identical; 5 new tests; CS is the spec source of record — fix(webview): invalidate per-view state after reset and import #981's parallelMode file is 1357 lines and lacks the F3 describes).
  • src/core/webview/tests/ClineProvider.spec.ts (34+/1−) — (a) the forward fix of the F3 resetState sentinel: F4's single global viewStates clear removes the key (real VS Code Memento semantics: update(key, undefined) deletes the key), so the F3-era toEqual({}) expectation becomes toBeUndefined(); the test intent (no persisted per-view entry after reset) is preserved and satisfied more strongly; (b) one new multi-instance test (gate-required): two live instances, one saves a view-local mode, the other calls resetState() — the sibling's view-local state is cleared, the sibling receives exactly one state post, and the caller receives exactly one (its final post).

Budget

  • a+d 343 vs the 400-soft / 1000-hard budget: under the 400-soft target (headroom 57); the 1000 hard cap is not approached.
  • Stryker-diff gate (vs 8da5c6e, final head 80c147f): 11 raw mutants across the 20 executable changed lines (importExport.ts 6, ClineProvider.ts 5): 11 Killed, 0 Survived, 0 NoCoverage, 0 Ignored; thresholds 100/100; exit 0 at the final head.
  • vitest: 309 passed (4 suites, 4 spec files) — per file: importExport.spec 54, ClineProvider.parallelMode 29, ClineProvider.sticky-mode 19, ClineProvider.spec 207 (sticky-mode + ClineProvider.spec included as regression sentinels for the resetState change).
  • check-types, eslint (--prune-suppressions, max-warnings 0; suppression counts flat-or-down), prettier (--end-of-line=auto): all pass — check-types exit 0 (the standing proof of the webviewMessageHandler no-change decision: the importSettings case passing the full ClineProvider type-checks against the extended ImportWithProviderOptions.provider type); eslint exit 0 on the touched files (suppression counts flat — eslint-suppressions.json is 0/0 in this commit); prettier --end-of-line=auto clean.

Port fidelity (coordinator-verified)

  • ClineProvider.ts: the broadcastResetToAllInstances method is ported from the exact fix(webview): invalidate per-view state after reset and import #981 diff text (declaration, JSDoc, body) hunk-by-hunk; the resetState wiring inserts the exact fix(webview): invalidate per-view state after reset and import #981 comment + call before the final postStateToWebview() (the base resetState already carries _clearViewLocalState() + clearPersistedViewState()). The global viewStates clear removes entries only — viewStateSchema holds no secrets (mode/currentApiConfigName/updatedAt), and the 50-entry prune cap (F2 tests) is unaffected by clearing.
  • src/core/webview/webviewMessageHandler.ts is 0/0 vs base. fix(webview): invalidate per-view state after reset and import #981's structural provider-wrapper hunk (the importSettings case carrying the broadcast callback) is REDUNDANT in this stack: the base importSettings case already passes the full provider object (provider: provider), which structurally satisfies the extended ImportWithProviderOptions.provider type (settingsImportedAt + postStateToWebview present; broadcastResetToAllInstances optional and present on the full ClineProvider after this port). The guarded call inside importSettingsWithFeedback therefore reaches the real method with zero WMH changes; the check-types gate is the standing proof.
  • importExport.ts: the two fix(webview): invalidate per-view state after reset and import #981 hunks verbatim (the optional method on ImportWithProviderOptions; the guarded broadcast block in importSettingsWithFeedback after the settingsImportedAt write).
  • importExport.spec.ts: the 3 fix(webview): invalidate per-view state after reset and import #981 tests ported with two adaptations: (1) lint-required — the raw provider-identifier string casts of the fix(webview): invalidate per-view state after reset and import #981 text are replaced with the providerIdentifiers.* constants (zoo/no-raw-provider-identifiers), no semantic change; (2) gate-required — the skip test gains a console.warn negative assertion (the fix(webview): invalidate per-view state after reset and import #981 text had none).
  • ClineProvider.spec.ts: exactly one assertion change — the F3 resetState sentinel ("should clear viewLocalState and the persisted entry when resetting state"): toEqual({} (the F3-era artifact: F3's last viewStates write was clearPersistedViewState() writing {}) becomes toBeUndefined() with a 2-line comment, because F4's mandated single global clear (contextProxy.setValue("viewStates", undefined)) forwards to updateGlobalState(key, undefined), which removes the key under real VS Code Memento semantics. The test's intent (no persisted per-view entry after reset) is preserved and satisfied more strongly; the fix(webview): invalidate per-view state after reset and import #981-mandated broadcast body is unchanged. Plus one new multi-instance test (gate-required, not from fix(webview): invalidate per-view state after reset and import #981 — see below).
  • ClineProvider.parallelMode.spec.ts: the F4 describes (CS L1675-L1789, with the L1674 blank separator — 116 lines total) appended byte-identical from the CS copy; nothing earlier in the file touched.
  • Stryker gate evidence (why the two test additions above exist): at the F3-head gate, the fix(webview): invalidate per-view state after reset and import #981/CS port alone left 5 Survived mutants — the importExport truthiness-guard mutant (ConditionalExpression -> "true", hidden because the guarded try/catch swallows the TypeError a missing method would throw) and 4 broadcastResetToAllInstances mutants (the _clearViewLocalState call site and the instance !== this condition, covered only by single-instance tests). fix(webview): invalidate per-view state after reset and import #981 was a closed draft that never ran this gate. The two additions (one CP.spec multi-instance test, one console.warn negative assertion) bring the gate to 0 Survived / 0 NoCoverage with no Stryker disable directives and no source changes.
  • DO-NOT-PORT verifications (per the fix(webview): invalidate per-view state after reset and import #981 file map): packages/types 3 files (index.test.ts / global-settings.ts / vscode-extension-host.ts) — already shipped by F1a/F1c (presence verified by content, 0/0 here); ClineProvider.spec.ts 2 hunks + ClineProvider.sticky-mode.spec.ts 4 hunks — F3-owned (shipped); webviewMessageHandler.ts + webviewMessageHandler.spec.ts — F1c territory / redundant (above); webview-ui 4 files (App.tsx, App.spec.tsx, ExtensionStateContext.tsx, utils/vscode.ts) — F7 / F1c territory (0/0 here).

Structural note on the parallelMode spec (coordinator-verified)

The CS parallelMode.spec.ts is 1790 lines: a shared preamble (L1-672), an F1-series test section (L673-1363: viewId uniqueness, local state isolation, saveViewState, stale temporary-id load), the F3 describes (L1364-1673), a blank separator (L1674), the F4 multi-instance describes (L1675-L1789), and the file's final top-level close (L1790). In this series the F1-series section lives in ClineProvider.spec.ts (shipped by F1a/F1b/F1c — the deliberate F1-series describe restructure), and the F2 unit shipped the persisted-pruning and #1065 retention tests inside the parallelMode file (absent from the CS parallelMode file). Both placements are behaviorally covered; the divergence is structural, not a coverage gap.

Series mechanics

  • Base of record: upstream/main @ 0d937c0; PR base is main; the branch is stacked on the F3 head 8da5c6e (the F1-series and F2/F3 heads merge below it in the series merge order).
  • Draft PR per unit; merge order F1a to F1b to F1c to F2 to F3 to F4 to F5 to F6 to F7.
  • CS not-ported register (for consistency): (1) kimi-code OAuth try/catch + routerModels.spec.ts +29; (2) ApiConfigManager.tsx min-w-0 shrink to grow; (3) ApiConfigManager.visual.tsx deletion + 2 PNG baselines; (4) mojibake comment; (5) unused defaultModeSlug import — resolved by F3; (6) providers/, .coderabbit.yaml, .github/, CONTRIBUTING.md, .gitignore churn.
  • Merge check against upstream main 4c7474d (merge-base = base of record 0d937c0), via git merge-tree on the full F0-to-F4 stack: tree e3af144dead05acf4fc681a33786d03dd4e1b681; auto-merges Task.ts, Task.spec.ts, ClineProvider.ts, ClineProvider.spec.ts; the sole conflict is src/eslint-suppressions.json (stage blobs base 0706dbe6fb5c / upstream 381cf0c1e03f / F4 73323b9f3c43 — F3's flat-suppression state vs upstream drift; resolved by mechanical prune at merge time).

@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Summary

Summary by CodeRabbit

  • New Features

    • Added persistent, per-view settings for modes and API configurations.
    • Added dedicated title-bar and command palette actions for editor tabs.
    • Editor-tab actions now target the correct tab instance.
  • Improvements

    • Prevented duplicate editor tabs when opening multiple times quickly.
    • Improved recovery when saved view settings or API profiles are unavailable.
    • Mode changes now remain associated with the correct task and view.
  • Bug Fixes

    • Settings import/export no longer transfers machine-local view state.
    • Reset and configuration updates now synchronize across active views.

Walkthrough

The change adds durable per-view mode and provider state, stable webview identifiers, provider-specific command routing, serialized tab creation, import/export isolation, and task-scoped mode switching. It also adds broad tests for persistence, lifecycle handling, profile repair, and storage fallback.

Changes

Per-view state and webview identity

Layer / File(s) Summary
State contracts and browser identity
packages/types/src/*, webview-ui/src/utils/*, webview-ui/src/context/*
Defines persisted view state and view identifiers. The webview generates and persists stable identifiers with storage fallbacks.
Provider-local persistence
src/core/webview/ClineProvider.ts, src/core/webview/__tests__/*
Stores mode and provider selections per view, merges local and shared state, validates modes, repairs profile pins, prunes persisted entries, and isolates instances.
Launch and mutation wiring
src/core/webview/webviewMessageHandler.ts, src/core/webview/__tests__/webviewMessageHandler.spec.ts
Registers view state during launch, repairs invalid selections, tolerates registration failures, and routes settings writes through the provider.

Panel commands and integrations

Layer / File(s) Summary
Panel command routing
src/activate/registerCommands.ts, src/activate/__tests__/registerCommands.spec.ts, src/package.json
Adds tab-specific commands, targets the correct provider instance, serializes tab creation, and protects tracked-panel references from stale disposal events.
Import, task, tool, and API integration
src/core/config/*, src/core/task/*, src/core/tools/*, src/extension/*
Excludes machine-local view state from import/export, broadcasts reset events after imports, scopes mode changes to tasks, and synchronizes API configuration through ClineProvider.

Priority: ➖ Normal

Estimated code review effort: 5 (Critical) | ~90 minutes

Merge Risk: 🟡 Moderate · up to 9004f

This change adds durable per-view state and multi-panel routing. A few edge cases should be resolved before merge: a legacy profile entry can wipe the saved API profile selection for all views on launch; deleting a profile can restore per-view pins to the deleted profile; and a failure while refreshing one open tab can stop a reset from clearing the remaining tabs. Normal flows appear covered by tests, but these paths can leave users with wrong or stale configuration after reset, import, or profile deletion.


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore (reviewers only)

❌ Failed checks (2 errors, 1 warning)

Check name Status Explanation Resolution
Persistence Integrity ❌ Error Changed persistence paths can leave stale or split state. ClineProvider.broadcastResetToAllInstances() clears viewStates with direct contextProxy.setValue("viewStates", undefined) calls at lines… Serialize reset/import invalidation through the same view-state write queue as all view-state mutations. Add an invalidation generation or barrier so writes that started before or during reset/import cannot recreate cleared entries. Make sh…
Lifecycle Resource Cleanup ❌ Error The changed Task.submitUserMessage path can perform stale task work after cancellation. At src/core/task/Task.ts:1805-1806, a mode submission now waits for taskModeReady and then calls `provider… Make the mode submission cancellation-aware. After waitForModeInitialization() and before handleModeSwitch, return when this.abort or this.abandoned is true, or when provider.getCurrentTask() !== this. Add the same target-task can…
Out of Scope Changes check ⚠️ Warning The raw summary includes many changes outside the stated F4 objective, including command registration, task-mode handling, provider profiles, webview state foundations, and UI utilities. The descripti… Rebase the PR onto the intended F3 stack base or split prerequisite changes into separate PRs. Ensure this PR contains only the F4 reset and settings-import invalidation changes and their tests.
✅ Passed checks (5 passed)
Check name Status Explanation
Regression Evidence ✅ Passed PASS. The changed behaviors have focused coverage at their lowest practical layers. Tests cover tab command routing, disposed or missing tab no-ops, command-post failures, tab creation reuse and seria…
Security Boundaries ✅ Passed No changed path meets the security failure conditions. The new durable view state stores only mode, currentApiConfigName, and updatedAt (packages/types/src/global-settings.ts); exports omit `v…
Linked Issues check ✅ Passed The description references tracking issue #41 and upstream issues #1561, #980, and #981, providing concrete issue linkage.
Title check ✅ Passed The title clearly identifies the main change: invalidating live sibling view state during reset and settings import.
Description check ✅ Passed The description is detailed, on-topic, and covers the issue references, implementation scope, tests, validation results, and porting decisions. It does not use every template heading or checklist item…
Full details: Persistence Integrity

Explanation

Changed persistence paths can leave stale or split state. ClineProvider.broadcastResetToAllInstances() clears viewStates with direct contextProxy.setValue("viewStates", undefined) calls at lines 3780-3788, but it does not use persistedViewStateWriteQueue. If a view-state save is already queued, the broadcast can complete and the queued save can then rewrite the old entry. Reset or import can therefore appear complete while stale state returns after reload. Also, changed ClineProvider.setValue() and setValues() write shared settings first and persist the per-view entry in a separate operation at lines 3652-3681 and 3689-3764. If the second write fails, the shared value is durable but the per-view value is not, with no rollback or partial-failure result. A later reload can apply the old per-view value and lose the user's new selection. The existing tests cover successful ordering and broadcast exceptions, but they do not cover these interleavings or partial writes.

Resolution

Serialize reset/import invalidation through the same view-state write queue as all view-state mutations. Add an invalidation generation or barrier so writes that started before or during reset/import cannot recreate cleared entries. Make shared-setting and per-view persistence one atomic transaction where possible; otherwise snapshot both values, roll back the first write when the second fails, and report the operation as partially failed. Update the in-memory view cache only after the durable operation succeeds. Add tests for a queued save racing with broadcast and for a per-view write rejection after the shared write succeeds.

Full details: Lifecycle Resource Cleanup

Explanation

The changed Task.submitUserMessage path can perform stale task work after cancellation. At src/core/task/Task.ts:1805-1806, a mode submission now waits for taskModeReady and then calls provider.handleModeSwitch(mode, this) without checking abort, abandoned, or whether the task is still current. If provider.getState() remains pending, the provider can evict the task first (abortTask(true) sets abort and removes it from the task registry), then the pending submission resumes. handleModeSwitchUnlocked still emits TaskModeSwitched, updates task history, writes the canceled task's mode, and can persist view state and post state (ClineProvider.ts:2099-2135). This creates stale transition work after cancellation and can duplicate state work when a replacement task starts.

Resolution

Make the mode submission cancellation-aware. After waitForModeInitialization() and before handleModeSwitch, return when this.abort or this.abandoned is true, or when provider.getCurrentTask() !== this. Add the same target-task cancellation/current-task guard in handleModeSwitch or handleModeSwitchUnlocked, before telemetry, event emission, history writes, and view-state persistence. Add a regression test that keeps getState() pending, starts submitUserMessage(..., mode), evicts or aborts the task, resolves getState(), and verifies that no mode switch, history update, view-state write, or message delivery occurs.

Full details: Out of Scope Changes check

Explanation

The raw summary includes many changes outside the stated F4 objective, including command registration, task-mode handling, provider profiles, webview state foundations, and UI utilities. The description claims a five-file scope, which conflicts with the supplied changeset summary.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch vps2/f4-cross-instance-reset
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the has-conflicts PR has merge conflicts with the base branch label Sep 7, 2026
@github-actions

github-actions Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Review status

Thanks for contributing. This comment tracks the review sequence and the next action.

Current step: Address automated review findings and push fixes.

After fixes are pushed and required CI passes, automated review restarts.

Review-state labels are managed by this workflow; do not edit them manually.

@codecov

codecov Bot commented Sep 7, 2026

Copy link
Copy Markdown

…en view-identity tests

Track the in-flight tab panel creation with a module-level promise so concurrent openClineInNewTab calls reuse one panel and provider (adds a Promise.all regression test). ClineProvider.spec sets the private view via the public resolveWebviewView() instead of a ts-ignore assignment. registerCommands.spec types evictCurrentTask/refreshWorkspace on the fixture and drops the as any attachment. eslint-suppressions: prune the registerCommands.spec.ts entry (two as any suppressions removed).
…-bar posts

- openClineInNewTab: extract the unserialized creation body into
  createTabPanelUnlocked and guard the in-flight slot clear so a settled
  creation cannot clobber a replacement already stored in the slot.
- onDidDispose: clear the tracked tab ref only when the disposing panel is
  still the tracked one, so a late disposal of a replaced panel cannot
  clobber the replacement's ref.
- MDM lookup failure: log the fallback to the output channel instead of
  swallowing it silently.
- Route the six title-bar button handlers through a shared postActions
  helper that posts each action in order and logs failures with the
  handler-specific prefix.
- package.json: add the four InTab commands to the command palette, scoped
  to the active tab panel.
- Tests: handler-level regression for openInNewTab + popoutButtonClicked
  started before the first creation resolves; fresh-creation test for a
  settled in-flight promise; stale-panel disposal regression; retained
  panel assertion for disposed tab instances; rightmost-editor column
  placement assertion; MDM fallback output assertion; %s placeholders for
  primitive it.each titles.
- Stryker directives for the two equivalent setPanel type-literal mutants
  (setPanel branches only on type === sidebar).
@easonLiangWorldedtech
easonLiangWorldedtech force-pushed the vps2/f4-cross-instance-reset branch 2 times, most recently from b9e8fb7 to 05f264b Compare September 7, 2026 20:07
Replace the weak toBeDefined() assertion in the dispose spec with an
identity check against the panel returned during creation, per the
CodeRabbit actionable comment on this PR (review run 7c4cfeb3-6dd9-4615-
9a58-70cfc705eca2). The tracked tab is now pinned with toBe(panel)
before the dispose assertions, so a wrong or duplicated tracked panel
fails the suite instead of passing a defined-only check.

Upstream: Zoo-Code-Org#1528 (vps2 F0)
@easonLiangWorldedtech
easonLiangWorldedtech force-pushed the vps2/f4-cross-instance-reset branch from 05f264b to eac3873 Compare September 7, 2026 20:24
Retain the tracked tab panel in the InTab handler cases and assert that
getInstanceForView was called with that exact panel, per the CodeRabbit
actionable comment on this PR (review run 4afe1273-8739-4235-90d3-311db5f6ccb9,
inline comment 3952466254 on the tabHandlerCases spec). A handler resolving
any other view now fails instead of passing on the stubbed provider result
alone; the same identity pin is applied to plusButtonClickedInTab.

Upstream: Zoo-Code-Org#1528 (vps2 F0)
…States

Each ClineProvider instance now owns a unique viewId (renderContext plus a
monotonic counter) and registers a stable viewStateId for durable persistence.

- Per-view state buffer (viewLocalState) holds mode / currentApiConfigName /
  apiConfiguration overrides in memory; saveViewState persists the non-secret
  subset durably under the active view id, rekeyed to the stable id on
  registration.
- viewStates is stored as a map pruned to the newest 50 entries; writes go
  through a serialized queue so concurrent provider instances merge without
  lost updates.
- setViewStateId sanitizes ids and rejects "__proto__" so a per-view entry can
  never be keyed through the Object.prototype setter.
- postMessageToWebview no longer awaits the webview ack: a remounted or
  disposed page never acknowledges, and awaiting would wedge task-critical
  callers.
- History restore falls back to the default mode view-locally instead of
  writing the shared global mode.
- GlobalState gains the "viewStates" key and GLOBAL_STATE_KEYS tracks it.

Adds F1a coverage in ClineProvider.spec.ts (viewId uniqueness, saveViewState
persistence semantics, loadViewState fallback and failure, pruning, the
__proto__ guard) and adapts the two history-restore tests in
ClineProvider.sticky-mode.spec.ts to the view-local restore. getState()
merging of hydrated per-view values and the remaining view-state suites land
in the follow-up (F1b).
@github-actions github-actions Bot added awaiting-author PR is waiting for the author to address requested changes has-conflicts PR has merge conflicts with the base branch and removed has-conflicts PR has merge conflicts with the base branch awaiting-author PR is waiting for the author to address requested changes labels Sep 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting-author PR is waiting for the author to address requested changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants