ContextProxy's cache is shared by every provider in the host, but nothing pulls a Memento write back into it

Aberta
#2,659 0 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 3 dias

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
18/100
Tipo de issue
Bug
Clareza
Razoavelmente clara
Status de atividade
Ativa
Stack de tecnologia
typescript, vscode
Domínio
backend

Direção de pesquisa

Start in src/core/config/ContextProxy.ts: getInstance (around :742-750) returns the static _instance without consulting the context, and initialize() (:90-131) is the only path that fills the cache from globalState. The probe spec and its results are in the issue body, but the probe file is not committed. Done means a Memento write made outside the proxy becomes visible after a chosen refresh entry point, without clobbering in-flight proxy writes, pinned in src/core/config/tests/ContextProxy.spec.ts.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

What happens

ContextProxy is a process-wide singleton: getInstance(context) returns the object the first caller created, whatever context a later caller passes, and its in-memory caches are filled only at construction time (initialize()) and by writes that go through the proxy. Inside one extension host that means a setting written through one ClineProvider is visible to every other provider without any storage read - and, in the other direction, a value written straight into a Memento (another extension, a legacy migration path, another window's host) is never seen by the running providers until something calls initialize() again. Only the first half works today, and it works silently.

Mechanism (every line number against 2a082ce5a42b1a22497d4eb32123482f69866567; src/core/config/ContextProxy.ts blob e53f60fb8381)

  • :732 - private static _instance: ContextProxy | null = null.

  • :742-750 - static async getInstance(context): returns this._instance when set (:743-745), otherwise constructs (:747) and awaits initialize() (:748). The context argument is not consulted once an instance exists, so a second, different ExtensionContext gets the first one's caches.

  • :90-94 copies every GLOBAL_STATE_KEYS entry from globalState into the cache, and :103 and :112 copy secrets from the Memento. This is the only path that fills the cache from storage without a write having gone through this proxy, and it runs once per process. Two reads do pull storage into the cache inside the write path, and both are guarded by write ownership: :423 (this.stateCache[key] = this.originalContext.globalState.get<GlobalState[K]>(key)) and :469 (if (this.secretWriteOwner.get(key) === owner) this.secretCache[key] = readBack).

  • :640 / :668 - setValue and setValues update the cache and then the Memento. Writes go the other way only.

  • Production reaches the singleton from src/extension.ts:183 and src/activate/registerCommands.ts:241, both await ContextProxy.getInstance(context), so every view and command in a window shares the one object. The ClineProvider constructor never builds its own proxy.

  • The same two functions are byte-identical at #2236's head (dd03278144, blob 64023b9b9cdb): getInstance sits at :826-834 and _instance at :816 there (initialize() stays at :107-131) because that PR adds lines elsewhere in the file - the region around :774 is resetAllState(), not the singleton. Verified by extracting and comparing the function texts, not by reading the hunk headers.

  • Code enumeration, no probe needed: no onDidChange subscription on a Memento exists anywhere in the tree.
    git grep -n -E "(globalState|workspaceState|memento)\.onDidChange" 2a082ce5a42b1a22497d4eb32123482f69866567 prints no output - and exit 1
    is git grep's "no match" status, not a failed command - the same for the whole tree and for -- src.
    git grep -n onDidChange 2a082ce5a42b1a22497d4eb32123482f69866567 -- src/core/config/ContextProxy.ts prints no output either. Nothing in the
    product subscribes to a storage change on the object whose cache this is, which is why the snapshot in
    initialize() is never refreshed.

  • Scale, so the claim is not read as a gap in the API: the subscription-shaped sites that do exist are countable
    in one command. git grep -n -E "\.onDidChange[A-Za-z_]*\\(" 2a082ce5a42b1a22497d4eb32123482f69866567 -- src prints 35 call sites, 6 inside test,
    mock and test-utils paths and 29 outside them, and not one of the 29 has a Memento receiver: four read a
    SecretStorage (src/services/zoo-code-auth.ts:46, src/services/mcp/McpHub.ts:1126 and :1244,
    src/services/mcp/SecretStorageService.ts:88). Named in full so nobody has to trust my category names: of the 29,
    13 are a bare .onDidChange( (SecretStorage plus FileSystemWatcher), 3 onDidChangeConfiguration, 2
    onDidChangeViewState, 2 onDidChangeActiveTextEditor, 2 onDidChangeWorkspaceFolders, and 1 each of
    onDidChangeVisibility, onDidChangeTelemetryEnabled, onDidChangeTextEditorSelection,
    onDidChangeTextEditorVisibleRanges, onDidChangeVisibleTextEditors, onDidChangeTerminalShellIntegration,
    onDidChangeTabs - 13 + 3 + 2 + 2 + 2 + 7 = 29. If you want the mention totals instead: git grep -n onDidChange 2a082ce5a42b1a22497d4eb32123482f69866567 -- src prints 222 lines, git grep -o on the same scope prints 227 occurrences, and the
    difference is lines carrying two identifiers. The same commands at #2236's head d4cde33064 give the same
    35 / 6 / 29 and the same 222 / 227, so nothing here depends on which of the two revisions you check.

Measured with a probe (deliberately not a committed test)

Two fake contexts A and B, separate Mementos backed by separate Maps whose get counts reads:

  1. ContextProxy.getInstance(b.context) === ContextProxy.getInstance(a.context), and B's Memento is read zero extra times to build it - getInstance returns before touching the new context.
  2. await proxyA.setValues({ currentApiConfigName: "written-by-instance-a" }) lands in A's Memento only (b.store.has(...) === false), yet proxyB.getValues().currentApiConfigName returns it with no additional read of B's Memento. This is the pair that separates 'shared' from 'merely cold'.
  3. A write that bypasses the proxy - b.memento.update("currentApiConfigName", "written-straight-into-b"), the shape of any other actor - changes B's storage but not what the cache reports: proxyB.getValues() still returns A's value.
Run Production under test Result
baseline blob 64023b9b9cdb at dd03278144 (tree 9c8718941a7a) Tests 1 passed (1), exit 0
main's own file blob e53f60fb8381 checked out from 2a082ce5a4, restored and blob-verified back Tests 1 passed (1), exit 0
the 'merely cold' alternative getInstance keyed on the context (if (this._instance && this._instance["originalContext"] === context)), so each context still gets its own initialize() seed and only the sharing is removed Tests 1 failed (1); the first assertion it reddens is the identity check at probe :73

Why this is worth an issue rather than a comment

The fork carries refs/heads/feat/cross-tab-state-invalidation (e7512a08b7, merge-base with main f2bdcb6da6). Its commits add exactly the mechanism the second half needs, but at the provider level and not at the cache level: 338af883b9 fix(webview): clear durable view state on reset broadcast calls instance._clearViewLocalState() and await instance.contextProxy.setValue("viewStates", undefined) for every live ClineProvider (+13/-6 with its parallel-mode spec), and 00e119677d fix: invalidate view-local state after reset and import does the same for imports through webviewMessageHandler.ts (+11/-1). Because the proxy is a singleton, those broadcasts invalidate the shared setting on every instance in the window for free - it is the same object - and what they must invalidate separately is the per-instance viewLocalState. The gap is the other direction: no path carries a change made outside this process (a second window's host, another extension, a settings edit that lands in the same Memento later) into the running cache. A second window is a separate host with its own singleton and its own initialize() snapshot. That nothing refreshes the snapshot from a storage event is a reading of the code - the probe never fires a storage event, so the claim comes from enumerating the code paths (no such reader exists) rather than from the measurement.

What a fix has to deal with (no fix proposed here)

  • One notification is already enough for the shared half - and that is what makes the other half visible.
    Because every provider in a window reads the same cache object, a single message that reaches any live
    provider invalidates the shared setting for all of them; that half is free. What a broadcast cannot get for
    free is the per-instance half: each ClineProvider carries its own viewStateId, its own claim token, and
    its own durable viewStates entry keyed by that id, so a reset that only touches the cache leaves those
    bindings pointing at state nothing re-reads. That is why the fork's changes land at the provider level
    while the cache itself stays stale, and why 'we notify every instance' does not answer this issue.
  • A re-entry point that is not initialize(). Re-running it (:90-94, chain :107-131) re-reads every GLOBAL_STATE_KEYS entry and every secret and overwrites the cache wholesale, which would clobber writes still in flight (the stateWriteOwner / stateWriteGenerations bookkeeping around :640). A refresh needs a generation-aware merge, not a re-seed.
  • A transport, not only a broadcast. broadcastResetToAllInstances reaches live ClineProvider objects inside one process. Cross-window needs something that survives a process boundary (a state-change message, or an explicit syncFromStorage() on a known event), and no such reader exists today.
  • A test at the right layer. A fix should pin in src/core/config/__tests__/ContextProxy.spec.ts that a Memento write made outside the proxy becomes visible after the chosen refresh entry point, and that an in-flight proxy write is not clobbered by it. Nothing in apps/vscode-e2e covers this today.

What this measurement does not say

  • It is one process with two ExtensionContext objects. It does not model two extension hosts, and no harness here launches a second window: the multi-window sentence is a reading of the code (_instance is a static, so it cannot cross a process), not a measured cross-process result.
  • In production the views do not each own a proxy, so the fixture fact 'a second view's proxy must be initialized explicitly or it reports the default for a key another view wrote' is a property of the fixture. The accurate production statement is that no production path hands a second view a cold proxy, because getInstance awaits initialize() on the one shared object.
  • initialize() takes a snapshot, so a proxy that seeded early and then received writes only through other proxies stays correct. Code that writes the Memento directly - the migrations around :150-343 read globalState directly - is the population that can drift.
  • The probe is not in the suite and adds no test rows; lane counts on the pushed branches are unchanged by this measurement.

Measured by the fixer lane (probe archived at .dsh/workflow/20261122-1551/tmp/crosstab-probe.spec.ts; logs crosstab-probe-head.txt, crosstab-probe-main.txt, crosstab-probe-mutant-alt.txt, the applied patch printed in the mutant log's header). Filed by the workflow lead. No code was written for this and no PR was touched.

Linguagem predominante
TypeScript
Estrelas
2k
Forks
301
Merge médio
3d 14h
PRs com merge (30d)
103

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de Zoo-Code-Org/Zoo-Code

Todas as issues de Zoo-Code-Org/Zoo-Code

Issues semelhantes

Mais issues de TypeScript

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.