Skip to content
2 changes: 2 additions & 0 deletions .oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
},
"rules": {
"sort-comparator-performance/no-repeated-collator": "warn",
"app-store-performance/no-state-ignoring-selector": "error",
"app-store-performance/no-tab-map-scan-in-selector": "error",
"app-store-performance/require-selector": "error",
"app-store-performance/no-identity-selector": "error",
"app-store-performance/no-fresh-selector-result": "error",
Expand Down
2 changes: 2 additions & 0 deletions config/oxlint-performance-audit.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
}
],
"rules": {
"app-store-performance/no-state-ignoring-selector": "warn",
"app-store-performance/no-tab-map-scan-in-selector": "warn",
"app-store-performance/require-selector": "warn",
"app-store-performance/no-identity-selector": "warn",
"app-store-performance/no-fresh-selector-result": "warn",
Expand Down
172 changes: 172 additions & 0 deletions config/oxlint-plugins/app-store-performance.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ function createRuleState() {
appStoreHooks: new Set(),
shallowHooks: new Set(),
namedSelectors: new Map(),
weakMaps: new Set(),
deferredCalls: []
}
}
Expand Down Expand Up @@ -271,6 +272,16 @@ function deferredSelectorRule(inspect) {
},
VariableDeclaration(node) {
recordNamedSelector(node, state)
if (isModuleScope(node)) {
for (const entry of node.declarations) {
if (
entry.init?.type === 'NewExpression' &&
identifierName(entry.init.callee) === 'WeakMap'
) {
state.weakMaps.add(identifierName(entry.id))
}
}
}
},
CallExpression(node) {
if (isAppStoreCall(node, state)) {
Expand Down Expand Up @@ -359,6 +370,165 @@ function noNestedFreshUnderShallowRule() {
})
}

/** Small state maps and imported helpers are deliberately outside this rule's scope. */
const SCANNED_MAPS = new Set([
'tabsByWorktree',
'unifiedTabsByWorktree',
'groupsByWorktree',
'browserTabsByWorktree',
'browserPagesByWorkspace',
'layoutByWorktree',
'terminalLayoutsByTabId',
'worktreesByRepo'
])

/** Walk one function body, including conditional branches, without descending into closures. */
function walkBody(node, visit) {
if (!node || typeof node !== 'object' || FUNCTION_NODES.has(node.type)) {
return
}
visit(node)
for (const [key, child] of Object.entries(node)) {
if (key === 'parent') {
continue
}
if (Array.isArray(child)) {
child.forEach((entry) => walkBody(entry, visit))
} else {
walkBody(child, visit)
}
}
}

function parameterNames(parameter) {
const names = new Set()
walkBody(parameter, (node) => {
if (
node.type === 'Identifier' &&
!(node.parent?.type === 'Property' && node.parent.key === node && !node.parent.computed)
) {
names.add(node.name)
}
})
return names
}

function noStateIgnoringSelectorRule() {
return deferredSelectorRule(({ selector }) => {
if (!selector) {
return null
}
const names = parameterNames(selector.params[0])
let referenced = false
// References inside nested callbacks still depend on the selector's snapshot.
const visit = (node) => {
if (!node || typeof node !== 'object') {
return
}
if (
node.type === 'Identifier' &&
names.has(node.name) &&
!(
node.parent?.type === 'MemberExpression' &&
node.parent.property === node &&
!node.parent.computed
) &&
!(node.parent?.type === 'Property' && node.parent.key === node && !node.parent.computed)
) {
referenced = true
}
for (const [key, child] of Object.entries(node)) {
if (key === 'parent') {
continue
}
if (Array.isArray(child)) {
child.forEach(visit)
} else {
visit(child)
}
}
}
visit(selector.body)
return referenced
? null
: {
node: selector,
message:
'This store selector ignores its state; read the supplied snapshot instead of doing state-independent work on every write.'
}
})
}

function scansTabMap(selector, state, depth = 0) {
const aliases = new Set()
const isMap = (node) => SCANNED_MAPS.has(propertyName(node)) || aliases.has(identifierName(node))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let scan = null
let cached = false
const helpers = []
walkBody(selector.body, (node) => {
if (node.type === 'VariableDeclarator' && isMap(node.init)) {
aliases.add(identifierName(node.id))
}
if (
node.type === 'BinaryExpression' &&
['===', '!=='].includes(node.operator) &&
(isMap(node.left) || isMap(node.right))
) {
cached = true
}
Comment thread
brennanb2025 marked this conversation as resolved.
Resolved
if (node.type === 'CallExpression') {
const method = propertyName(node.callee)
if (
method === 'get' &&
state.weakMaps.has(identifierName(node.callee.object)) &&
node.arguments.some(isMap)
) {
cached = true
}
if (
identifierName(node.callee.object) === 'Object' &&
['keys', 'values', 'entries'].includes(method) &&
isMap(node.arguments[0])
) {
scan ??= node
}
const helper = state.namedSelectors.get(identifierName(node.callee))
if (helper) {
helpers.push(helper)
}
}
if (node.type === 'ForInStatement' && isMap(node.right)) {
scan ??= node
}
})
if (cached) {
return null
}
if (scan || depth === 1) {
return scan
}
for (const helper of helpers) {
const found = scansTabMap(helper, state, depth + 1)
if (found) {
return found
}
}
return null
}

function noTabMapScanInSelectorRule() {
return deferredSelectorRule(({ selector, state }) => {
const scan = selector && scansTabMap(selector, state)
return scan
? {
node: scan,
message:
'Do not enumerate tabsByWorktree, unifiedTabsByWorktree, groupsByWorktree, browserTabsByWorktree, browserPagesByWorkspace, layoutByWorktree, terminalLayoutsByTabId, or worktreesByRepo on every selector run; cache an index by map identity.'
}
: null
})
}

function bindContext(createVisitors) {
return (context) => {
const visitors = createVisitors()
Expand All @@ -372,6 +542,8 @@ function bindContext(createVisitors) {
export default {
meta: { name: 'app-store-performance' },
rules: {
'no-state-ignoring-selector': { create: bindContext(noStateIgnoringSelectorRule) },
'no-tab-map-scan-in-selector': { create: bindContext(noTabMapScanInSelectorRule) },
'require-selector': { create: bindContext(requireSelectorRule) },
'no-identity-selector': { create: bindContext(noIdentitySelectorRule) },
'no-fresh-selector-result': { create: bindContext(noFreshSelectorResultRule) },
Expand Down
76 changes: 76 additions & 0 deletions config/scripts/app-store-performance-plugin.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ function lintSources(sources) {
pluginPath,
sources,
rules: {
'app-store-performance/no-state-ignoring-selector': 'warn',
'app-store-performance/no-tab-map-scan-in-selector': 'warn',
'app-store-performance/require-selector': 'warn',
'app-store-performance/no-identity-selector': 'warn',
'app-store-performance/no-fresh-selector-result': 'warn',
Expand Down Expand Up @@ -75,6 +77,60 @@ const sources = {
const Delegating = () => useAppStore((state) => buildRows(state))
const NestedDelegating = () => useAppStore(useShallow((state) => ({ ids: buildRows(state) })))
`,
ignoringState: `
import { useAppStore } from '@/store'
import { useShallow } from 'zustand/react/shallow'
const selectConstant = (state) => constant
const Zero = () => useAppStore(() => readCurrent())
const Unused = () => useAppStore(useShallow((state) => constant))
const Named = () => useAppStore(selectConstant)
`,
scanningMaps: `
import { useAppStore } from '@/store'
const findChatTab = (state, sessionId, owner) => {
const tabsByWorktree = state.unifiedTabsByWorktree
for (const worktreeId in tabsByWorktree) {
const tab = structuredChatTabBySessionId(tabsByWorktree, worktreeId, sessionId)
if (tab && ownerForTab(state, tab) === owner) return tab
const qualified = tab && tabsByWorktree[worktreeId]?.find(candidate => ownerForTab(state, candidate) === owner)
if (qualified) return qualified
}
return undefined
}
const Sender = () => useAppStore(state => local && sessionId ? findChatTab(state, sessionId, owner) : undefined)
const Direct = () => useAppStore(state => Object.values(state.tabsByWorktree))
const Keys = () => useAppStore(state => Object.keys(state.worktreesByRepo).length)
const Aliased = () => useAppStore(state => {
const m = state.groupsByWorktree
if (enabled) for (const key in m) inspect(key)
return state.activeId
})
`,
cachedMaps: `
import { useAppStore } from '@/store'
const cache = new WeakMap()
const cached = state => {
const map = state.unifiedTabsByWorktree
const hit = cache.get(map)
if (hit) return hit
const value = Object.values(map)
cache.set(map, value)
return value
}
let previous, value
const identityCached = state => {
if (previous !== state.tabsByWorktree) {
value = Object.entries(state.tabsByWorktree)
previous = state.tabsByWorktree
}
return value
}
const Weak = () => useAppStore(state => cached(state))
const Identity = () => useAppStore(state => identityCached(state))
const Snapshot = () => useAppStore(({ active }) => active)
const Callback = () => useAppStore(state => lookup(() => state.active))
const External = () => useAppStore(state => importedIndex(state))
`,
cachedHelpers: `
import { useAppStore } from '@/store'
import { useShallow } from 'zustand/react/shallow'
Expand Down Expand Up @@ -161,3 +217,23 @@ describe('app store performance Oxlint plugin', () => {
expect(diagnostics).toEqual([])
})
})

describe('per-write selector work', () => {
it('reports inline, shallow, and named state-ignoring selectors', () => {
expect(diagnosticsBySource.get(sources.ignoringState).map(({ code }) => code)).toEqual([
'app-store-performance(no-state-ignoring-selector)',
'app-store-performance(no-state-ignoring-selector)',
'app-store-performance(no-state-ignoring-selector)'
])
})
it('follows conditional sender helpers and local collection aliases', () => {
expect(
diagnosticsBySource
.get(sources.scanningMaps)
.filter(({ code }) => code === 'app-store-performance(no-tab-map-scan-in-selector)')
).toHaveLength(4)
})
it('allows same-file WeakMap and identity-guard caches', () => {
expect(diagnosticsBySource.get(sources.cachedMaps)).toEqual([])
})
})
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { translate } from '@/i18n/i18n'
import { useAppStore } from '@/store'
import type { AppState } from '@/store/types'
import { structuredChatTabBySessionId } from '@/lib/structured-chat-tab-index'
import {
structuredChatTabBySessionId,
structuredChatWorkspacesBySessionId
} from '@/lib/structured-chat-tab-index'
import { useStructuredChatTabConversationName } from '@/runtime/structured-conversation-name'
import {
structuredAgentSessionOwnerForTab,
Expand All @@ -23,7 +26,7 @@ function findChatTab(
executionHostId: string | null
): Tab | undefined {
const tabsByWorktree = state.unifiedTabsByWorktree
for (const worktreeId in tabsByWorktree) {
for (const worktreeId of structuredChatWorkspacesBySessionId(tabsByWorktree, sessionId)) {
const tab = structuredChatTabBySessionId(tabsByWorktree, worktreeId, sessionId)
if (tab && structuredAgentSessionOwnerForTab(state, tab) === executionHostId) {
return tab
Expand Down
Loading
Loading