GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(storage): handle empty JSON files gracefully by coleleavitt · Pull Request #7888 · anomalyco/opencode

Conversation

@coleleavitt

@coleleavitt coleleavitt commented Jan 12, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Fixes #7889
Fixes #7715

Summary

Fixed "Unexpected end of JSON input" and "Unterminated string" errors in storage and SDK client.

1. SDK Client (both v1 and v2 client.gen.ts)

  • Handle empty responses with proper JSON parsing check
  • Added try-catch with contextual error messages for malformed JSON

2. Storage Layer - Empty Files (storage.ts - commit 23848ed)

  • Handle empty JSON files gracefully in read() and update() functions
  • Check for empty files before parsing, throw NotFoundError instead of JSON parse error

3. Storage Layer - Corrupted Files (storage.ts - commit 061652e)

  • NEW: Detect null bytes and control characters in JSON files
  • NEW: Comprehensive JSON parse error handling with descriptive messages
  • NEW: Make stats command resilient to corrupted files

Root Cause (Corrupted Files)

Found 3 production storage files containing 1518 null bytes each instead of valid JSON:

  • .trim() check only catches whitespace, not null bytes
  • JSON.parse() crashed with "Unterminated string" error
  • stats command failed because Promise.all() had no error handling

Changes

SDK Client

// Read response as text first, only parse JSON if non-empty
const text = await response.text()
if (!text) return undefined
data = JSON.parse(text)

Storage - Empty File Check

const content = await Bun.file(target).text()
if (!content.trim()) {
  throw new NotFoundError({ message: `Empty file: ${target}` })
}

Storage - Corruption Detection (NEW)

// Detect null bytes and control characters
const hasControlCharacters = /[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(content)
if (hasControlCharacters) {
  throw new NotFoundError({ message: `Corrupted file detected: ${target}` })
}

// Wrap JSON.parse with error handling
try {
  const result = JSON.parse(content)
  return result as T
} catch (e) {
  const message = e instanceof Error ? e.message : String(e)
  throw new NotFoundError({ message: `Failed to parse JSON from ${target}: ${message}` })
}

Stats Command Resilience (NEW)

// Skip corrupted files gracefully instead of crashing
const projects = await Promise.all(
  projectKeys.map((key) => Storage.read<Project.Info>(key).catch(() => undefined))
)

Testing

  • ✅ Detected and handled 3 corrupted files in production storage
  • ✅ opencode-dev stats works (processed 4,773 sessions successfully)
  • ✅ All type checks pass
  • ✅ Empty file handling works as expected

Files Changed

  • packages/opencode/src/storage/storage.ts - Empty + corrupted file handling
  • packages/opencode/src/cli/cmd/stats.ts - Resilient error handling
  • SDK client files (auto-generated) - Empty response handling

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@github-actions github-actions Bot added the needs:issue label Jan 12, 2026
@github-actions

github-actions Bot commented Jan 12, 2026

Copy link
Copy Markdown
Contributor

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions

github-actions Bot commented Jan 12, 2026

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

Potential Duplicate Found:

PR #7618: fix(sdk): improve JSON parsing error handling with contextual messages
#7618

Why it's related: This PR also addresses JSON parsing errors in the SDK. Both PRs are fixing issues with JSON parsing in the SDK client, though PR #7618 appears to focus on error handling with contextual messages while PR #7888 (the current PR) specifically handles empty response bodies. These may be tackling related or overlapping issues in the same codebase area.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@coleleavitt
fix(sdk): handle empty JSON response bodies gracefully
2b848ef
Fixes 'Unexpected end of JSON input' error when server returns empty body.

Root cause: OPTIONS handler at /zen/v1/models returned status 200 with null body,
but SDK only handled empty responses for status 204 or Content-Length: 0.

Changes:
- Server: OPTIONS handler now returns 204 (No Content) instead of 200
- SDK (v1 & v2): JSON parsing now reads text first and handles empty bodies
  by returning {} instead of failing on response.json()
@coleleavitt
coleleavitt force-pushed the fix/json-parse-empty-response branch from 2ed9637 to 2b848ef Compare January 12, 2026 00:48
@coleleavitt

coleleavitt commented Jan 12, 2026

Copy link
Copy Markdown
Contributor Author

Created issue #7889 to track this bug. PR description updated with Fixes #7889.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot removed the needs:issue label Jan 12, 2026
@coleleavitt coleleavitt mentioned this pull request Jan 12, 2026
Unexpected end of json #7715
Closed
@coleleavitt
fix(tui): handle undefined agent during initial data load after login
e59a836
After Anthropic OAuth login, sync.data.agent is empty while data loads.
This caused crashes when accessing local.agent.current().name before
agents were populated.

Changes:
- Make agentStore.current nullable with optional chaining on init
- Add fallback to first agent in current() when not found
- Add early return guards in submit(), cycle(), cycleFavorite(), set()
- Add null checks in highlight(), spinnerDef() memos
- Use optional chaining in JSX for agent name display
This was referenced Jan 12, 2026
fix: handle empty JSON responses in sdk client #8027
Closed
fix: gracefully handle invalid json response #8104
Closed
@mrlubos

mrlubos commented Jan 13, 2026

Copy link
Copy Markdown
Contributor

@coleleavitt the client crash will be fixed upstream hey-api/hey-api#3202

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@coleleavitt
fix(storage): handle empty JSON files gracefully
23848ed
- Check for empty files before parsing to avoid 'Unexpected end of JSON input' error
- Throw NotFoundError instead of JSON parse error for empty files
- Apply fix to both read() and update() functions
@coleleavitt coleleavitt changed the title fix(sdk): handle empty JSON response bodies gracefully fix(storage): handle empty JSON files gracefully Jan 14, 2026
@coleleavitt
fix: prevent crashes from corrupted JSON files in storage
061652e
- Add null byte/control character detection in storage read/update
- Wrap JSON.parse in try-catch with descriptive error messages
- Make stats command resilient to corrupted files by catching errors
- Fixes 'JSON Parse error: Unterminated string' crashes in stats command
@coleleavitt

coleleavitt commented Jan 15, 2026

Copy link
Copy Markdown
Contributor Author

Additional Fix: Corrupted File Detection

Added comprehensive error handling for corrupted JSON files containing null bytes or control characters.

New Changes (commit 061652e)

Problem Found:

  • Found 3 storage files with 1518 null bytes each (instead of valid JSON)
  • .trim() check only catches whitespace, not null bytes
  • JSON.parse() failed with "Unterminated string" error
  • stats command crashed because Promise.all() had no error handling

Solution:

  1. Corruption Detection - Added null byte/control character check in storage.ts:

    const hasControlCharacters = /[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(content)
    if (hasControlCharacters) {
      throw new NotFoundError({ message: `Corrupted file detected: ${target}` })
    }
  2. JSON Parse Error Handling - Wrapped JSON.parse() in try-catch with descriptive errors

  3. Resilient Stats Command - Made stats.ts skip corrupted files gracefully:

    Storage.read<Project.Info>(key).catch(() => undefined)

Testing:

  • ✅ Detected and handled 3 corrupted files in production storage
  • ✅ opencode-dev stats now works (processed 4,773 sessions successfully)
  • ✅ All type checks pass

This prevents the "JSON Parse error: Unterminated string" crash that occurred with corrupted storage files.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@mrlubos

mrlubos commented Jan 15, 2026

Copy link
Copy Markdown
Contributor

@coleleavitt do you think this check also belongs upstream?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot mentioned this pull request Jan 16, 2026
fix: skip corrupted session files when listing sessions #8825
Closed
@coleleavitt
merge: resolve conflict with dev (keep currentAgent + add .catch())
39ffa63
@coleleavitt
coleleavitt marked this pull request as draft January 16, 2026 16:23
@coleleavitt coleleavitt mentioned this pull request Jan 16, 2026
chore(sdk): update @hey-api/openapi-ts to 0.90.4 #8921
Merged
@mrlubos

mrlubos commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

cc @coleleavitt ^

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@coleleavitt coleleavitt closed this Jan 16, 2026
@coleleavitt

coleleavitt commented Jan 16, 2026

Copy link
Copy Markdown
Contributor Author

Closing - the main issue (SDK crash on empty responses) was fixed upstream via the hey-api update in PR #8921.

The storage layer fixes for corrupted local files are nice-to-have but not critical enough to warrant a separate PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@coleleavitt
coleleavitt deleted the fix/json-parse-empty-response branch January 16, 2026 19:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

SDK throws 'Unexpected end of JSON input' on empty response bodies Unexpected end of json

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@coleleavitt @mrlubos
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.