Skip to content

fix(ai-vault): read legacy OpenCode JSON message parts - #50781

Merged
nwparker merged 1 commit into
mainfrom
bugbash/pr-50643
Nov 27, 2026
Merged

nwparker merged 1 commit into
mainfrom
bugbash/pr-50643

Conversation

@nwparker

@nwparker nwparker commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Older versions of OpenCode saved each chat as lots of small files: one per message, plus separate files that hold what was actually said. Orca opened the message files but never the ones with the text, so old OpenCode chats showed up in History and search with nothing in them. Orca now opens those text files too, so old chats show their prompts and replies again and can be searched.

Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​204 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​204
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​146 $\color{#cf222e}{\Huge{\mathbf{−}}}$​51 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​95

What Changed

Before: in legacy OpenCode sessions (storage/message/<sessionId>/*.json), History showed no first prompt and only a summary preview, the transcript was empty, and search never indexed the message bodies. The First Prompt card sent these .json sessions to the SQLite worker, which returned nothing.

After: prompts, previews, transcripts and search all come back for these sessions.

How:

  • session-scanner-opencode-parser.ts: when a message has no inline content, read storage/part/<message file key>/*.json and sort by part file name (the part ID), which is how OpenCode's MessageV2.parts does it. Tool parts become tool_use/tool_result blocks for the shared decoder.
  • Tool input and outcome normalization moved out of the SQLite capture into session-scanner-opencode-tool-state.ts. The JSON reader uses it too, so read/edit/write calls index with their filePath.
  • Part reads are bounded by mode:
    • Listing reads parts only for the newest messages, until 6 preview-bearing messages turn up or 100 messages have been read (the same window as the SQLite preview query).
    • The on-demand first-prompt read only reads user messages until it finds the prompt.
    • The full transcript/search parse reads every part.
  • session-first-user-prompt-read.ts: OpenCode .json paths now go to the file parser instead of the SQLite worker.
  • One-time repairs, each gated by a marker:
    • Parse-cache rows for OpenCode *.json paths are dropped (opencode_json_parts_rows_version).
    • Search cursors for those paths are reset so they get reindexed (opencode_json_parts_files_version, via a new optional path glob on filesRepairSql).
    • SQLite-backed db# OpenCode rows and other agents are not touched.

Why

OpenCode's legacy MessageV2 storage keeps metadata and content in separate files. I checked this against upstream source (packages/opencode/src/session/message-v2.ts at v1.1.15): parts() lists ["part", <message key>] and sorts by part ID. On a real legacy store, no message file had inline content, so every one of these sessions came up empty. Fixing only the reader would not have been enough, because existing parse-cache rows and up-to-date search cursors would keep the empty results. That is why the change includes the one-time repairs.

Linked Issue

Fixes #50642

Supersedes #50643. Original fix by @Afloat16 in #50643 (authorship kept on the commit).

Visual Proof

N/A for screenshots. The change is in the main-process transcript parser and no UI code changed. The before/after below is data from a probe run on a read-only copy of a real legacy OpenCode store (6 sessions, 59 messages, 221 parts), the same input on both sides. prompt is the first-prompt length in characters, previews and transcript are counts.

Session main this PR
ses_4650dd5b (6 msgs) prompt=0 previews=1 transcript=0 prompt=116 previews=4 transcript=12
ses_4a6c17f8 (2 msgs) prompt=0 previews=1 transcript=0 prompt=2 previews=2 transcript=2
ses_4650a20f (3 msgs) prompt=0 previews=1 transcript=0 prompt=41182 previews=3 transcript=4
ses_46503e17 (40 msgs) prompt=0 previews=1 transcript=0 prompt=429 previews=5 transcript=117
ses_4a6bffe1 (2 msgs) prompt=0 previews=1 transcript=0 prompt=2 previews=2 transcript=2
ses_46503c9c (6 msgs) prompt=0 previews=1 transcript=0 prompt=494 previews=4 transcript=32

Edge fixture (a file-only first message, malformed part JSON, a message with no part directory, step/patch/pending-tool/errored-tool parts):

  • main: first prompt is undefined and the transcript is [].
  • this PR: first prompt is "Second prompt" and the transcript has the bash, errored, read and user entries. Nothing crashes.

Testing

  • I manually tested these changes locally (parser probe against a real legacy OpenCode store, macOS)
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

New tests:

  • session-scanner-opencode-json-parts.test.ts covers four things:
    • Parts are read in part-ID order and tool input is normalized.
    • Listing previews, count and truncated flag match a full parse while reading 12 part dirs instead of 40.
    • The real readAiVaultFirstUserPrompt entry point returns Prompt 0 with 1 part-dir read.
    • On main, the prompt is undefined. On the previous branch head, first-prompt returned {prompt:null} and did 13 reads.
  • session-search-opencode-parts-repair.test.ts: the OpenCode JSON cursor resets to -1 once, while the SQLite and Claude cursors stay at 100, and a later cursor of 200 survives a reopen. This fails on main, where the cursor stays at 100.

Parse-cache repair: no repo test, checked by hand. Rows written by the real SessionParseCacheDatabase.write were round-tripped with POSIX and Windows paths: OpenCode .json rows (and copilot rows, from that existing repair) are dropped, db# and Claude rows survive, and a second open does nothing. On a snapshot of a real cache, the filter matched 0 of 2818 rows.

Commands run:

  • vitest run src/main/ai-vault/scanners/opencode/ src/main/ai-vault-search/storage/ src/main/ai-vault/parse-cache/ src/main/ai-vault/prompts/: 8 files, 16 tests pass.
  • oxlint, oxfmt --check, anti-slop oxlint, code-quality native-plugin oxlint, ast-grep and the changed-code quality gate are clean on the 9 touched files.
  • Platform: macOS. Paths use join/basename and the existing WSL-gated fs reads. The parse-cache filter was checked with Windows paths.

Performance

This runs in the AI Vault scanner and search indexer, using async fs only. It does not add sync I/O, subprocesses or polling, and it changes nothing in the renderer, stores or caches, so the work per update does not grow with N tabs (0 extra calls per update at N=200). Parses are cached by session-file mtime, and legacy JSON sessions stop changing once OpenCode moves to SQLite, so each session pays the cost once, plus the one forced re-read from the repair.

Per-session parse time, using real temp files, median of 7 runs on a loaded machine:

shape (msgs x parts) listing, main listing, PR search, PR
10x4 2.0 ms 5.0 ms 2.9 ms
40x6 2.5 ms 5.1 ms 12.0 ms
500x8 33-39 ms 34-36 ms 200-287 ms
2000x10 127-144 ms 123-141 ms 1007-1368 ms
  • Main reads no part files at all, so the search-path cost is the minimum work needed to index content that was never read before. It runs once per session in the background indexer.
  • The longest event-loop gap on listing was 1-9 ms.
  • First prompt: 40x4 takes 2.7-3.1 ms and 400x6 takes 26-27 ms, and one failing SQLite worker spawn per card open is gone.
  • The real store's listing parse took 1.8-27.8 ms per session.

Risk

Level: Low

  • The riskiest part is the one-time repair. After the upgrade, legacy OpenCode JSON sessions are re-parsed and re-indexed once in the background.
  • The repairs only touch derived cache and search state. The OpenCode session and part files are never written. Inline content still wins when it is present.
  • Mixed versions sharing userData: an older build can write empty rows again, and they would not be repaired a second time.
  • Backing out is a plain revert, but it would not restore the dropped cache rows or reset cursors. Normal scans rebuild them.

Review

The contributor's approach is unchanged. Follow-ups by the maintainer:

  • Part dirs are keyed by the message file name, as OpenCode does. A readdir name cannot contain separators, so no traversal check is needed.
  • Tool-state normalization is shared with the SQLite reader.
  • Part reads are bounded on the listing and first-prompt paths.
  • First-prompt reads for .json sessions go to the file parser.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Known limits, unchanged from the SQLite path:

  • Synthetic text parts are not filtered out.
  • JSON tool parts produce two transcript entries (tool_use/tool_result), the shape the shared decoder uses.

Security, SSH/remote and mobile are unaffected: there are no new endpoints or wire shapes.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Legacy OpenCode (MessageV2 JSON storage) keeps message metadata in
storage/message/<sessionId>/*.json and the content in
storage/part/<messageKey>/<partId>.json. The parser only read inline
message content, so these sessions showed no first prompt, previews or
transcript in History and conversation search.

Read part files when inline content is absent, keyed by the message file
name and sorted by part ID as OpenCode does, and map tool parts through
the tool-state normalization shared with the SQLite reader. Listing
parses read parts only for the newest preview window, and first-prompt
reads only for user messages until the prompt is found. The First Prompt
card now sends legacy .json sessions to the file parser instead of the
SQLite worker.

One-time marker-gated repairs drop stale parse-cache rows and reset
search cursors for OpenCode JSON sessions only.

Fixes #50642

Co-authored-by: Neil <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The OpenCode JSON scanner now reads separately stored message parts and uses them for transcript content, tool records, previews, and first-user prompts. OpenCode JSON prompt reads bypass the SQLite worker. One-time repairs invalidate affected parse-cache rows and limit the search cursor repair to JSON paths.

Severity of issue fixed: Medium

Merge Risk: Low · up to e3169

OpenCode JSON sessions now show prompts and previews from separately stored part files. A run of blank-text messages at the end of a session can hide earlier previews. Listing also does bounded extra file reads for each affected session. Neither issue is serious, but both are worth addressing or accepting before merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(ai-vault): read legacy OpenCode JSON message parts" matches the main change. The PR makes the scanner read separately stored part files for legacy OpenCode JSON sessions, which restores…
Description check Passed The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #50642), Visual Proof (N/A with a reason and probe data), Testing with checkboxes and commands…
Linked Issues check Passed Issue #50642 requires the following coding behavior. Each item maps to changed code in the PR summary and the head file read.

1. Read separately stored parts. session-scanner-opencode-parser.ts reads…
Out of Scope Changes check Passed All changed areas connect to issue #50642 or to the code paths needed to deliver it:
- session-scanner-opencode-parser.ts and session-scanner-opencode-tool-state.ts: part reading and shared tool norma…
Full details: Title check

Explanation

The title "fix(ai-vault): read legacy OpenCode JSON message parts" matches the main change. The PR makes the scanner read separately stored part files for legacy OpenCode JSON sessions, which restores prompts, previews, transcripts, and search. The title is concise, specific, and follows a conventional-commit style.

Full details: Description check

Explanation

The description follows the repository template. It includes ELI5, What Changed, Why, Linked Issue (Fixes #50642), Visual Proof (N/A with a reason and probe data), Testing with checkboxes and commands, Performance with a measured table, Risk with Level: Low and a rollback note, Review, Agent skill boundary, Notes, and Checklist. The AI Disclosure section is empty, but the template says to fill it only for non-StablyAI members, so this is acceptable. The Performance section starts with the required 'None, because' phrasing, but the text that follows is a longer analysis, which is acceptable. The description is thorough and specific.

Full details: Linked Issues check

Explanation

Issue #50642 requires the following coding behavior. Each item maps to changed code in the PR summary and the head file read.

  1. Read separately stored parts. session-scanner-opencode-parser.ts reads storage/part/<message key>/*.json when inline content is absent, sorts by part file name, and maps tool parts to tool_use/tool_result. Covered by the parser summary and session-scanner-opencode-json-parts.test.ts.
  2. First prompt, previews, transcript, and search. Listing, first-prompt, and full-parse modes read parts as the issue requires. session-first-user-prompt-read.ts routes OpenCode .json sessions to the file parser. Covered by the summary.
  3. Tool input and outcome normalization. session-scanner-opencode-tool-state.ts is shared by the JSON and SQLite readers.
  4. One-time cache repair. session-parse-cache-database.ts drops OpenCode .json parse-cache rows once, gated by opencode_json_parts_rows_version.
  5. One-time search cursor repair. session-search-schema.ts (read at head) adds opencode_json_parts_files_version with pathGlob '*.json', scoped to agent = 'opencode'. The UPDATE sets byte_offset to PARTIAL_FILE_CURSOR (-1) only for those rows. The marker is then recorded as '1', so later opens skip the repair. Claude and SQLite rows are not touched because their paths do not match *.json under agent 'opencode'.
  6. Regression tests. session-search-opencode-parts-repair.test.ts asserts the JSON cursor moves to -1, the SQLite and Claude cursors stay at 100, and a later 200 survives reopen.

Limits: the parse-cache repair has no automated repository test. The PR reports only a manual check for it. The issue's validation section describes a baseline check, so the behavior is implemented, but the automated coverage for that repair is absent. The diff tool was unavailable for the changed blobs, so the verdict relies on the head file read and the PR summary for the other files.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to issue #50642 or to the code paths needed to deliver it:

  • session-scanner-opencode-parser.ts and session-scanner-opencode-tool-state.ts: part reading and shared tool normalization for legacy JSON sessions.
  • session-first-user-prompt-read.ts: routes OpenCode .json first-prompt reads to the file parser, as the issue requires.
  • session-parse-cache-database.ts and session-search-schema.ts: the one-time repairs the issue specifies. The search repair is restricted to agent 'opencode' and *.json paths, so other agents remain unchanged.
  • session-scanner-opencode-sqlite-capture.ts: refactored to use the shared tool helpers. This prevents divergent tool normalization between the SQLite and JSON readers.
  • session-scanner-messages.ts: exports SESSION_PREVIEW_MESSAGE_LIMIT (value unchanged), which supports the bounded listing read.
  • Test files: support the requirements above.
    No change was found that is unrelated to the linked issue.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eeab0c35-1737-41b0-8acf-df41462794ed
Commits

Reviewing files that changed from the base of the PR and between ac427c1 and e3169d7.

Files selected for processing: 9

  • src/main/ai-vault-search/storage/session-search-opencode-parts-repair.test.ts
  • src/main/ai-vault-search/storage/session-search-schema.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-database.ts
  • src/main/ai-vault/parsing/session-scanner-messages.ts
  • src/main/ai-vault/prompts/session-first-user-prompt-read.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-json-parts.test.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-tool-state.ts
  • src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-capture.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +172 to +173
if (blocks.some((block) => block.kind === 'text')) {
previews++

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Count only text that the preview path accepts when bounding the preview scan.

readOpenCodePreviewTail stops after six messages whose blocks contain any text block. The forward preview path rejects some of that text. Whitespace-only text, hidden-context-only text, and visual-directive-only text produce no preview in addPreviewMessage. A run of such messages can stop the reverse scan before it reaches earlier messages with usable text. Those earlier parts are never read, so their previews are lost and the listing falls back to summary text or no preview.

Use the same normalization in the predicate that the forward path uses:

Suggested fix

-import { normalizeTitleText } from '../../parsing/session-scanner-text-normalization'
+import {
+  extractPreviewContentText,
+  normalizeTitleText
+} from '../../parsing/session-scanner-text-normalization'
     const { blocks } = decodeSessionMessage(role, content, null, { includeTools: false })
-    if (blocks.some((block) => block.kind === 'text')) {
+    const textParts = blocks.flatMap((block) => (block.kind === 'text' ? [block.text] : []))
+    if (extractPreviewContentText(textParts, role) !== null) {
       previews++
     }

@nwparker
nwparker merged commit 0cd7d53 into main Nov 27, 2026
56 checks passed
@nwparker
nwparker deleted the bugbash/pr-50643 branch November 27, 2026 10:30
@Afloat16

Afloat16 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up on the same OpenCode contribution

This updates the existing handoff for #50643 and its merged continuation, #50781. The candidate adapts the three original review corrections to the maintained implementation and addresses the later preview acceptance review. It remains follow-up work on this contribution.

Candidate source: 981975040d7d71e231eb3c31965f9f0d5d9eb18f, based on 6a8e7f533cf9f6e40afbc090ac35f42efb2e9b79. Immutable candidate diff. The exact candidate passed all seven focused tests and all 28 checks selected by the repository's complete required gate.

Preserved maintained behavior

The adaptation keeps message-filename keys for part directories, filename ordering, shared OpenCode tool-state normalization, inline-content precedence, and the existing 100-message preview scan window. It also preserves the maintained legacy JSON First Prompt routing and its separate first-prompt read. The original record-ID directory case is not treated as a regression against this implementation.

Historical reproduction on the merged source

The exact-source reproduction job checked out e3169d781e15bf9e41f03b3caf4fb113604e4279 and verified that production files were unchanged. It confirmed three failing behavior scenarios and one passing maintainer control:

  • After a same-length assistant-part edit and reopening both persistent stores, History retained draftquery instead of finalquery, and Search found no updated text. A changed dependency revision also retained the previous failed-revision count.
  • After repeated ordinary part-read refusals, removing the refusal did not recover the expected prompt/search result across store restarts, despite unchanged part size, mtime and ctime.
  • The parser combined final text with earlier reasoning before the tool call/result, emitting five records where the expected producer order required six.

The bounded listing/First Prompt control passed: 12 part-directory reads for that listing fixture and one for First Prompt. The reproduction job succeeded because it confirmed those expected outcomes; the three production scenarios failed. The earlier 51431 complete gate applies to the original branch, not this adapted candidate.

Dependency freshness and read recovery

For the freshness review, a separate dependency signature records message/part metadata without altering the session file's real mtime, size or byte offsets. It participates in History cache reuse, persisted rows, Search read decisions, worker snapshots and failed-revision accounting. Additive schema changes remain transactional and preserve existing cached data.

After SQLite duplicates are excluded, discovery observes at most four retained legacy sessions concurrently. It enumerates message files and filename-keyed part directories, then records their metadata. Normal observation reads no message or part bodies. Only a part metadata failure triggers a message-body read to determine whether that dependency is used: inline content, another role or malformed JSON can make the inaccessible subtree irrelevant. Each message's part hash is incorporated only after successful observation.

This is O(M + P) metadata work for the observed messages and parts. The 12/1 control describes the parser fixture's bounded content-read path, not the total I/O of discovery.

For the ordinary I/O review, filesystem refusals remain distinct from readable malformed JSON. Required source failures discard the incomplete Search replacement without advancing a complete cursor or exhausting the unchanged-revision retry budget. Malformed JSON remains skippable. The recovery scenario retains repeated failures, persistent-store reopening and unchanged-stat assertions.

Emission order and visible preview counting

For the order review, only legacy OpenCode messages using nullish-content fallback opt into text/reasoning runs flushed around tool blocks. Default callers and inline messages keep their existing behavior; first-user prompt and preview extraction still use the whole decoded message. Each emitted run retains its 262,144 UTF-16 code-unit limit. This is a per-run cap, not an aggregate per-message cap, so preserving separated runs can increase total retained text.

The preview cutoff now follows the same two-stage acceptance as the final preview consumer: extractPreviewContentText, then normalizePreviewText. A text block can become empty only at the second stage—for example, removing a hidden-context prefix can expose a standalone visual directive. Such blocks must not count toward the six visible previews used to stop the reverse scan. The 100-message window remains unchanged.

Exact-source verification

The unused-directory/filename scenario now calls ordinary History listing through scanAiVaultSessions, with First Prompt checked separately through readAiVaultFirstUserPrompt. Both initial/updated preview assertions and the inline prompt assertion remain. The invisible-preview fixture separately retains its full-reader control and listing assertion. A test-only overlay on exact parent d9a05c3882c493d04fbc521c6f4031b85f2babcb reproduced a genuine listing assertion failure while its production files remained unchanged: the listing returned [] instead of ['Earlier useful preview.']. The job then restored the exact final candidate before its passing checks.

  • Exact-parent red proof: confirmed in the same verification job; one expected behavior assertion failed on d9a05c38, with no production overlay or setup/import failure.
  • Final four-file run: 7 tests passed, including the original freshness/repeated-I/O/order cases, default emission compatibility, unused-directory and filename behavior, the maintained bounded/First Prompt control and the strengthened preview fixture.
  • Complete required pnpm check:changed --base=6a8e7f533cf9f6e40afbc090ac35f42efb2e9b79 --maxWorkers=2: 28 checks passed in the exact-source job, including unit tests, typechecking, changed-code quality, formatting, lint, import boundaries, localization and the selected ratchets.

The job verified the candidate/base commit IDs and finished with tracked sources unchanged. These follow-ups are ready for review on the existing contribution; they are not an additional improvement count.

Afloat16 added a commit to Afloat16/orca that referenced this pull request Nov 27, 2026
Follow up on stablyai#50781 review 4718252235. Match the forward preview normalization when counting the bounded reverse scan so whitespace-only and hidden-context-only parts cannot hide earlier visible previews.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Legacy OpenCode JSON sessions lose separately stored message bodies in History and search

2 participants