The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop no-op adapter swaps notifying the thread runtime + derive backend venv from the selected interpreter
kshitijk4poor4019518edd66
diff --git a/apps/desktop/electron/backend-python-coherence.test.ts b/apps/desktop/electron/backend-python-coherence.test.tsnew file mode 100644index 00000000000..753ec534547--- /dev/null+++ b/apps/desktop/electron/backend-python-coherence.test.ts@@ -0,0 +1,107 @@+import assert from 'node:assert/strict'+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++import { test } from 'vitest'++// ── Regression guard: backend interpreter / site-packages coherence ─────────+//+// Live repro (2026-08-23, macOS dev run): the checkout had BOTH venvs —+// .venv/ → Python 3.12 (dev tooling)+// venv/ → Python 3.11 (the CLI install venv, owns the real deps)+//+// findPythonForRoot() prefers `.venv/bin/python` (3.12), but+// createPythonBackend() hardcodes `venvRoot = path.join(root, 'venv')` and+// puts venv/lib/python3.11/site-packages on PYTHONPATH. The 3.12 interpreter+// then imports 3.11-compiled native wheels and dies on the FIRST import:+// ImportError: No module named 'pydantic_core._pydantic_core'+// → backend exits(1) before ready → "Gateway offline" → renderer falls back+// to a dead 127.0.0.1:9119 and every profile fails to activate.+//+// The invariant these tests pin down: the venv whose interpreter is selected+// and the venv whose site-packages go on PYTHONPATH must be THE SAME venv.+// One resolver must own that decision (AGENTS.md "observable ladder" rule 6).++const here = path.dirname(fileURLToPath(import.meta.url))+const mainTsSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8')++function extractFunction(source: string, name: string): string {+ const start = source.indexOf(`function ${name}(`)+ assert.notEqual(start, -1, `function ${name} not found in main.ts`)++ // Slice to the next top-level `function ` declaration — crude but stable+ // for the flat function layout main.ts uses.+ const rest = source.slice(start)+ const next = rest.slice(1).search(/\nfunction /)++ return next === -1 ? rest : rest.slice(0, next + 1)+}++test('findPythonForRoot preference order includes .venv before venv (context for the coherence tests)', () => {+ const fn = extractFunction(mainTsSource, 'findPythonForRoot')+ const venvIdx = fn.indexOf("'.venv'")+ const plainIdx = fn.indexOf("'venv'")++ assert.notEqual(venvIdx, -1, 'expected findPythonForRoot to probe .venv')+ assert.notEqual(plainIdx, -1, 'expected findPythonForRoot to probe venv')+ assert.ok(venvIdx < plainIdx, '.venv is probed before venv — this ordering is what the hardcoded venvRoot below disagrees with')+})++// Fixed: createPythonBackend derives venvRoot from the selected interpreter+// via venvRootForPython(python, root), falling back to root/venv only for a+// system python. This test guards against re-hardcoding the venv path.+test('createPythonBackend derives venvRoot from the selected interpreter, not a hardcoded venv path', () => {+ const fn = extractFunction(mainTsSource, 'createPythonBackend')++ // The buggy shape: interpreter picked by findPythonForRoot (may be .venv),+ // while venvRoot/PYTHONPATH is unconditionally root/venv.+ const hardcodesVenv = /venvRoot\s*=\s*path\.join\(root,\s*'venv'\)/.test(fn)+ const derivesFromPython = /findPythonForRoot|python/.test(fn) && !hardcodesVenv++ assert.ok(+ derivesFromPython,+ 'createPythonBackend hardcodes venvRoot=path.join(root, "venv") while findPythonForRoot may select .venv/bin/python — ' ++ 'a root with both venvs gets a 3.12 interpreter with 3.11 site-packages on PYTHONPATH and crashes on the first native import'+ )+})++// Pure-logic mirror of the same invariant, testable without main.ts exports:+// given a root where BOTH .venv and venv exist, whatever venv the interpreter+// came from must be the venv used for site-packages. This encodes the fix's+// contract so the implementation can be extracted against it later.+export function coherentVenvRootForPython(pythonPath: string, root: string): string | null {+ // The venv root is the directory two levels up from <venv>/bin/python+ // (Scripts/python.exe on Windows). A system interpreter (outside `root`)+ // is NOT a venv — pairing it with any venv's site-packages needs the same+ // version check, so it returns null here.+ const posix = pythonPath.match(/^(.*)\/bin\/python[0-9.]*$/)+ const win = pythonPath.match(/^(.*)[\\/]Scripts[\\/]python\.exe$/i)+ const candidate = posix?.[1] ?? win?.[1] ?? null++ if (!candidate) {+ return null+ }++ const normalizedRoot = root.replace(/\\/g, '/').replace(/\/+$/, '')+ const normalizedCandidate = candidate.replace(/\\/g, '/')++ return normalizedCandidate.startsWith(`${normalizedRoot}/`) ? candidate : null+}++test('coherentVenvRootForPython maps a selected interpreter back to ITS venv root', () => {+ assert.equal(coherentVenvRootForPython('/repo/.venv/bin/python', '/repo'), '/repo/.venv')+ assert.equal(coherentVenvRootForPython('/repo/venv/bin/python', '/repo'), '/repo/venv')+ assert.equal(coherentVenvRootForPython('C:\\repo\\venv\\Scripts\\python.exe', 'C:\\repo'), 'C:\\repo\\venv')+ assert.equal(coherentVenvRootForPython('/usr/bin/python3', '/repo'), null)+})++test('dual-venv root: site-packages must come from the venv that owns the selected interpreter', () => {+ // Simulates the live repro: interpreter resolved to .venv (3.12), so the+ // ONLY coherent venvRoot for PYTHONPATH is .venv — never the sibling venv.+ const selected = '/repo/.venv/bin/python'+ const venvRoot = coherentVenvRootForPython(selected, '/repo')++ assert.equal(venvRoot, '/repo/.venv')+ assert.notEqual(venvRoot, '/repo/venv', 'pairing a .venv interpreter with venv/ site-packages is the crash from the live repro')+})diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 0351a5396bd..28af53a2524 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -2480,6 +2480,35 @@ function getVenvPython(venvRoot) {return path.join(venvRoot, IS_WINDOWS ? path.join('Scripts', 'python.exe') : path.join('bin', 'python'))}+// Map a selected interpreter back to the venv that OWNS it (the directory+// above bin/ or Scripts/), but only when that venv lives inside `root`.+// Returns null for system pythons — they own no site-packages we should mount.+//+// This exists because findPythonForRoot() probes `.venv` before `venv`, and a+// checkout can legitimately have BOTH (dev tooling venv + the CLI install+// venv, possibly on different Python versions). The interpreter and the+// site-packages placed on PYTHONPATH must come from the SAME venv: pairing a+// .venv 3.12 python with venv/lib/python3.11/site-packages makes the backend+// die on its first native import (pydantic_core) before the gateway binds —+// the renderer then reports "Gateway offline" on every profile.+function venvRootForPython(python: string, root: string) {+ const parent = path.dirname(python)+ const binName = path.basename(parent).toLowerCase()++ if (binName !== 'bin' && binName !== 'scripts') {+ return null+ }++ const candidate = path.dirname(parent)+ const relative = path.relative(root, candidate)++ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {+ return null+ }++ return candidate+}+// Windows console-window flashes are governed by the *parent's* console, not by// each child spawn. A GUI-subsystem parent (pythonw.exe) has no console, so every// console-subsystem child it spawns (git, gh, cmd, ...) must allocate its own —@@ -4401,7 +4430,12 @@ function createPythonBackend(root, label, backendArgs, options: any = {}) {return null}- const venvRoot = path.join(root, 'venv')+ // The venv whose interpreter we selected is the venv whose site-packages+ // belong on PYTHONPATH — findPythonForRoot may have picked `.venv` over+ // `venv`, and mixing the two crashes the backend on its first native+ // import (see venvRootForPython). Fall back to root/venv only for a+ // system python, where the historical layout is the best guess.+ const venvRoot = venvRootForPython(python, root) ?? path.join(root, 'venv')const venvPython = getVenvPython(venvRoot)const command = IS_WINDOWS && fileExists(venvPython) ? venvPython : pythondiff --git a/apps/desktop/src/lib/incremental-external-store-runtime.ts b/apps/desktop/src/lib/incremental-external-store-runtime.tsindex 1ccc5121d97..e8e5fdcee2a 100644--- a/apps/desktop/src/lib/incremental-external-store-runtime.ts+++ b/apps/desktop/src/lib/incremental-external-store-runtime.ts@@ -151,14 +151,25 @@ class IncrementalExternalStoreThreadRuntimeCore extends ExternalStoreThreadRunticonst oldStore = self._storeself._store = store+ // Track whether anything OBSERVABLE changed. ChatRuntimeBoundary passes a+ // fresh adapter literal on every render, so identity churn of the adapter+ // object itself is NOT a change — notifying on it lets a subscriber whose+ // notification re-renders the boundary drive an unbounded feedback loop+ // (render -> new literal -> setAdapter -> notify -> render), which React+ // kills with "Maximum update depth exceeded" and takes the session tile+ // down with its error boundary.+ let changed = false+if (this.extras !== store.extras) {this.extras = store.extras+ changed = true}const newSuggestions = store.suggestions ?? EMPTY_ARRAYif (!shallowEqual(this.suggestions, newSuggestions)) {this.suggestions = newSuggestions+ changed = true}const newCapabilities = {@@ -178,10 +189,16 @@ class IncrementalExternalStoreThreadRuntimeCore extends ExternalStoreThreadRuntiif (!shallowEqual(self._capabilities, newCapabilities)) {self._capabilities = newCapabilities+ changed = true}if (oldStore && oldStore.isRunning === store.isRunning && oldStore.messageRepository === store.messageRepository) {- self._notifySubscribers()+ // Same transcript, same run state: notify only if extras/suggestions/+ // capabilities actually moved. A silent no-op swap here is what breaks+ // the render feedback loop — see the render-loop guard test.+ if (changed) {+ self._notifySubscribers()+ }return}@@ -220,7 +237,7 @@ class IncrementalExternalStoreThreadRuntimeCore extends ExternalStoreThreadRunti}}-class IncrementalExternalStoreRuntimeCore extends BaseAssistantRuntimeCore {+export class IncrementalExternalStoreRuntimeCore extends BaseAssistantRuntimeCore {threads: ExternalStoreThreadListRuntimeCoreconstructor(adapter: ExternalStoreAdapter) {diff --git a/apps/desktop/src/lib/incremental-runtime-adapter-notify.test.ts b/apps/desktop/src/lib/incremental-runtime-adapter-notify.test.tsnew file mode 100644index 00000000000..28067181ddc--- /dev/null+++ b/apps/desktop/src/lib/incremental-runtime-adapter-notify.test.ts@@ -0,0 +1,143 @@+/**+ * Regression tests for the bot-chat tile crash observed live on 2026-08-23:+ *+ * [error-boundary:contrib:session-tile:20260823_213059_ed6222]+ * Error: Maximum update depth exceeded. The result of getSnapshot should be+ * cached to avoid an infinite loop.+ * at UseTapEffects (assistant-ui internal)+ * at AuiProvider+ * at ChatRuntimeBoundary (src/app/chat/index.tsx)+ * at TileChat / SessionTilePane (src/app/chat/session-tile.tsx)+ *+ * Mechanism under test: ChatRuntimeBoundary passes a FRESH adapter object+ * literal to useIncrementalExternalStoreRuntime on every render. The+ * [runtime, store] effect therefore re-runs each render, and+ * IncrementalExternalStoreThreadRuntimeCore.__internal_setAdapter's+ * "nothing changed" fast path (same isRunning + same messageRepository)+ * still calls _notifySubscribers() unconditionally. A subscriber whose+ * notification re-renders the boundary then produces:+ * render -> new store literal -> effect -> setAdapter -> notify -> render+ * an unbounded feedback loop that trips React's update-depth guard and+ * takes the whole session tile down with the error boundary.+ *+ * The invariant pinned here: handing __internal_setAdapter an adapter that is+ * a NEW OBJECT but semantically identical (same messageRepository identity,+ * same isRunning, same capabilities) must NOT notify subscribers. Notify is+ * for observable state changes, not for object-identity churn of the adapter+ * literal — the render loop is impossible once no-op swaps are silent.+ */+import { fromThreadMessageLike, getAutoStatus } from '@assistant-ui/core/internal'+import type { ExportedMessageRepository, ExternalStoreAdapter, ThreadMessage } from '@assistant-ui/react'+import { describe, expect, it } from 'vitest'++import { IncrementalExternalStoreRuntimeCore } from './incremental-external-store-runtime'++const STATUS = getAutoStatus(false, false, false, false, undefined)++function message(id: string, text: string): ThreadMessage {+ return fromThreadMessageLike({ role: 'assistant', content: [{ type: 'text', text }] }, id, STATUS)+}++function repositoryOf(messages: ThreadMessage[]): ExportedMessageRepository {+ return {+ headId: messages.at(-1)?.id ?? null,+ messages: messages.map((item, index) => ({+ message: item,+ parentId: index === 0 ? null : messages[index - 1].id+ }))+ }+}++function adapterWith(messageRepository: ExportedMessageRepository, extra: Partial<ExternalStoreAdapter> = {}) {+ // Deliberately a fresh object each call — mirrors the inline literal in+ // ChatRuntimeBoundary (src/app/chat/index.tsx) whose closures (onNew,+ // onCancel, ...) are re-created per render.+ return {+ messageRepository,+ isRunning: false,+ setMessages: () => {},+ onNew: async () => {},+ onCancel: async () => {},+ ...extra+ } as ExternalStoreAdapter+}++describe('IncrementalExternalStoreThreadRuntimeCore adapter swap notifications', () => {+ it('does NOT notify subscribers when a new adapter object carries identical state (render-loop guard)', () => {+ const repo = repositoryOf([message('a', 'one'), message('b', 'two')])+ const core = new IncrementalExternalStoreRuntimeCore(adapterWith(repo))+ const thread = core.threads.getMainThreadRuntimeCore()++ let notifications = 0+ thread.subscribe(() => {+ notifications += 1+ })++ // Simulate 5 renders of ChatRuntimeBoundary: each passes a NEW adapter+ // literal with the SAME messageRepository identity and same isRunning.+ for (let render = 0; render < 5; render += 1) {+ core.setAdapter(adapterWith(repo))+ }++ // The live bug: this was 5 — one notify per render, each notify able to+ // schedule the next render. Silent no-op swaps break the feedback loop.+ expect(notifications).toBe(0)+ })++ it('still notifies when the message repository actually changes', () => {+ const repo = repositoryOf([message('a', 'one')])+ const core = new IncrementalExternalStoreRuntimeCore(adapterWith(repo))+ const thread = core.threads.getMainThreadRuntimeCore()++ let notifications = 0+ thread.subscribe(() => {+ notifications += 1+ })++ const grown = repositoryOf([message('a', 'one'), message('b', 'two')])+ core.setAdapter(adapterWith(grown))++ expect(notifications).toBeGreaterThan(0)+ })++ it('still notifies on an isRunning flip (turn start/stop must reach the thread UI)', () => {+ const repo = repositoryOf([message('a', 'one')])+ const core = new IncrementalExternalStoreRuntimeCore(adapterWith(repo))+ const thread = core.threads.getMainThreadRuntimeCore()++ let notifications = 0+ thread.subscribe(() => {+ notifications += 1+ })++ core.setAdapter(adapterWith(repo, { isRunning: true }))++ expect(notifications).toBeGreaterThan(0)+ })++ it('a subscriber that swaps a fresh-but-identical adapter on every notify must not recurse unboundedly', () => {+ // Direct simulation of the feedback loop: the subscriber plays the role of+ // React re-rendering ChatRuntimeBoundary (new literal -> setAdapter). With+ // the bug, every setAdapter notifies, the subscriber re-enters setAdapter,+ // and only the depth guard stops it. Fixed behavior: the first no-op swap+ // is silent, so the subscriber never fires and depth stays 0.+ const repo = repositoryOf([message('a', 'one')])+ const core = new IncrementalExternalStoreRuntimeCore(adapterWith(repo))+ const thread = core.threads.getMainThreadRuntimeCore()++ let depth = 0+ thread.subscribe(() => {+ depth += 1++ if (depth > 25) {+ throw new Error('Maximum update depth exceeded (simulated): adapter no-op swaps are notifying subscribers')+ }++ core.setAdapter(adapterWith(repo))+ })++ core.setAdapter(adapterWith(repo))++ expect(depth).toBe(0)+ })+})