-
Notifications
You must be signed in to change notification settings - Fork 14.4k
Non-null assertions on find() results can cause runtime crashes #11702
Copy link
Copy link
Open
Description
Summary
Several locations in the codebase use non-null assertions (!) on find() results, which will crash at runtime if the element is not found.
Locations
packages/opencode/src/acp/agent.ts:1264- `.find((c) => c.name === cmd.name)!`packages/opencode/src/cli/cmd/tui/context/local.tsx:57- `.find((x) => x.name === agentStore.current)!`packages/opencode/src/provider/provider.ts:1051- `Object.keys(mod).find((key) => key.startsWith("create"))!`packages/opencode/src/session/compaction.ts:99- `.findLast((m) => m.info.id === input.parentID)!.info as MessageV2.User`packages/opencode/src/session/summary.ts:124- `.find((m) => m.info.id === input.messageID)!`
Issue
// Example from provider.ts:1051
const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
// If no key starts with "create", find() returns undefined
// The ! assertion bypasses the type check but crashes at runtimeThe ! (non-null assertion) operator tells TypeScript to trust that the value is not null/undefined, but if find() doesn't match any element, it returns undefined, causing "Cannot read property 'X' of undefined" errors.
Impact
- Severity: Medium
- Type: Runtime Error
- Effect: Crashes when search predicate doesn't match
Suggested Fix
Replace non-null assertions with proper null checks:
// Option 1: Guard clause
const key = Object.keys(mod).find((key) => key.startsWith("create"))
if (!key) {
throw new Error(\`Provider module \${model.api.npm} has no create function\`)
}
const fn = mod[key]
// Option 2: Optional chaining with fallback
const fn = mod[Object.keys(mod).find((key) => key.startsWith("create")) ?? ""]
if (!fn) {
throw new Error(...)
}Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels