Skip to content

Non-null assertions on find() results can cause runtime crashes #11702

@riftzen-bit

Description

@riftzen-bit

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

  1. packages/opencode/src/acp/agent.ts:1264 - `.find((c) => c.name === cmd.name)!`
  2. packages/opencode/src/cli/cmd/tui/context/local.tsx:57 - `.find((x) => x.name === agentStore.current)!`
  3. packages/opencode/src/provider/provider.ts:1051 - `Object.keys(mod).find((key) => key.startsWith("create"))!`
  4. packages/opencode/src/session/compaction.ts:99 - `.findLast((m) => m.info.id === input.parentID)!.info as MessageV2.User`
  5. 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 runtime

The ! (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(...)
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions