Repository navigation
Add first prompt to agent session history rows - #12085
Conversation
Re-parse transcripts on demand to extract and display the untruncated first user prompt for copy/reuse. List scans omit the body (payload/perf); UI loads it when session details expand. Grok sessions extract the typed ask from <user_query> envelope, skipping injected <user_info> bootstrap rows. Supports Claude, Codex, Grok, and OpenCode agents.
AiVaultSessionDetails exceeded the 400-line oxlint limit after adding first-prompt UI; move SessionTime into its own module.
Corrupt transcripts now resolve null instead of rejecting the IPC call, matching behavior for other unavailable cases. OpenCode SQLite parsing now correctly captures all text parts from the earliest user message only, fixing truncation of large prompts and padding of small ones. Add stale-response guard in the UI to prevent late results from overwriting the current session when tabs switch. Consolidate text slicing via `sliceAtCodeUnitLimit` to avoid surrogate-pair splits across all callers.
Ensure truncation at safety limits doesn't split UTF-16 surrogate pairs, preventing corruption of astral characters in captured prompts.
Remounting the card on session switches prevents late responses from a previous load from writing stale data into the component's refs. Also improves conversation-turn key stability.
Greptile SummaryThis PR introduces three cohesive changes: it adds a
Confidence Score: 5/5Safe to merge; all behavioral changes are gated behind the new truncation flag and the on-demand re-parse path ensures the user always sees the correct first prompt even in degraded cases. The core logic — ring-buffer eviction sets the flag, sessionFirstPrompt gates on it, FirstPromptCard always falls back to the on-demand re-parse — is correct and well-tested. The refactoring of resume-command construction and parser file splits is purely additive. The one notable edge case (SQLite probe counting parts instead of messages) has no data-correctness impact and degrades only to an extra loading spinner. Files Needing Attention: src/main/ai-vault/session-scanner-opencode-sqlite.ts — the LIMIT N+1 probe works at part granularity rather than message granularity, which can cause unnecessary on-demand re-parses for sessions whose messages carry multiple text parts.
|
| Filename | Overview |
|---|---|
| src/main/ai-vault/session-scanner-accumulator.ts | Adds previewMessagesTruncated flag, seedFirstUserPrompt guard, and addPreviewContent helper; ring-buffer eviction now sets the flag when the window overflows. Logic is correct. |
| src/main/ai-vault/session-scanner-opencode-sqlite.ts | Adds LIMIT N+1 probe to detect preview-window truncation in the SQLite path. The probe counts part-table rows (not distinct messages), so a message with multiple text parts can produce a false-positive previewMessagesTruncated; consequence is an unnecessary on-demand re-parse rather than wrong data. |
| src/shared/ai-vault-session-display.ts | New sessionFirstPrompt function correctly gates on previewMessagesTruncated before using the sliding preview window as a first-prompt source. Logic and tests are complete. |
| src/shared/ai-vault-resume-command.ts | Pure extraction of resume-command construction from ai-vault-types.ts; all quoting helpers, codex-home env prefix, and platform routing are moved verbatim. |
| src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx | FirstPromptCard correctly initializes loading state lazily, races the on-demand re-parse against a 15 s deadline, and clears the dedupe handle on StrictMode cleanup so remounts never strand in loading state. |
| src/main/ai-vault/session-scanner-opencode-parser.ts | Extracted from secondary-parsers; seedFullFirstUserPrompt is called from real message.content (not the AI summary fallback), fixing the summary-seeding bug; addPreviewMessage receives seedFirstUserPrompt: false to avoid double-seeding. |
| src/main/ai-vault/session-scanner-agent-parser.ts | Clean router that dispatches to the per-agent parse functions; all agents accounted for in the switch. |
| src/main/ai-vault/session-first-user-prompt-read.ts | On-demand re-parse entry point; routes OpenCode SQLite sessions to readFirstUserPromptFromOpenCodeDb (direct DB query) instead of the preview-window path, correctly bypassing truncation issues. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["List scan / on-demand re-parse"] --> B["addPreviewMessage / addPreviewContent"]
B --> C{"previewMessages.length > 5?"}
C -- "No" --> D["previewMessagesTruncated = false"]
C -- "Yes (ring-buffer evicts oldest)" --> E["previewMessagesTruncated = true"]
F["OpenCode SQLite path"] --> G["LIMIT N+1 probe"]
G --> H{"probedRows.length > N?"}
H -- "No" --> D
H -- "Yes" --> E
D & E --> I["finalizeSession → AiVaultSession"]
I --> J["sessionFirstPrompt()"]
J --> K{"firstUserPrompt stored?"}
K -- "Yes" --> L["Return stored full prompt"]
K -- "No" --> M{"previewMessagesTruncated?"}
M -- "Yes" --> N["Return null → trigger on-demand re-parse"]
M -- "No" --> O["Return earliest user preview turn"]
N --> P["FirstPromptCard: on-demand getFirstUserPrompt IPC"]
P --> Q["15 s deadline race"]
Q --> R["Display full prompt text"]
Reviews (5): Last reviewed commit: "capture first user prompt by ordering Op..." | Re-trigger Greptile
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAI Vault session scanning now records preview truncation and full first-user prompts. Local sessions can reparse transcripts through a validated IPC API, while remote sessions return no prompt. The renderer displays fallback or loaded prompts and supports copying. Copilot, Cursor, Hermes, and OpenCode parsing now uses dedicated modules. Resume command construction moved to a shared module with shell-specific quoting and Codex environment handling. SSH proxy handling moved to a dedicated utility module. SSH and relay formatting changes preserve behavior. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ai-vault/session-scanner-accumulator.ts (1)
155-190: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winMove
firstUserPromptseeding before the preview-empty return.
addPreviewMessagereturns before the inline seeding block whentextis empty afternormalizePreviewText, but the rawargs.textmay still be a valid full first prompt.consumeOpenCodeMessagesandconsumeCopilotRecordLinerely on this inline seeding, so the first-user-turn suppression now has to match both preview and full-prompt normalization rules. Try seeding fromargs.textbefore returning, and still avoid adding any preview-only normalization asfirstUserPrompt.
🧹 Nitpick comments (2)
src/renderer/src/lib/ai-vault-resume-command.ts (1)
1-6: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider renaming the renderer wrapper to avoid a same-name collision with the new shared module.
This file and
src/shared/ai-vault-resume-command.tsshare the exact same basename. Mobile's equivalent wrapper avoids this by using a distinct name (ai-vault-resume-launch.ts). A shared basename between the builder module and its renderer wrapper makes editor file-search and import autocomplete ambiguous.Rename this file to something like
ai-vault-resume-launch.tsorai-vault-resume-command-renderer.tsto match the mobile naming pattern.src/main/ai-vault/session-first-user-prompt-read.test.ts (1)
124-137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a case for the non-local
executionHostIdguard.
readAiVaultFirstUserPromptreturns{ prompt: null }for any host other thanLOCAL_EXECUTION_HOST_ID. The web preload fallback and the renderercanLoadFullFirstPromptguard both depend on that contract. No test covers it, so a change to the host check would pass silently.💚 Proposed test for the remote-host guard
+ it('returns null for non-local execution hosts without reading the transcript', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-first-prompt-remote-')) + tempRoots.push(root) + const filePath = join(root, 'session.jsonl') + await writeFile( + filePath, + JSON.stringify({ + type: 'user', + sessionId: 'remote-session', + timestamp: '2026-05-01T10:00:00.000Z', + message: { role: 'user', content: 'Should not be returned' } + }) + ) + + await expect( + readAiVaultFirstUserPrompt({ + agent: 'claude', + filePath, + executionHostId: 'ssh:build-box' + }) + ).resolves.toEqual({ prompt: null }) + })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ef8d3291-62a4-4ec0-9c75-27c16a8b84d4
📒 Files selected for processing (46)
mobile/src/session/ai-vault-resume-launch.tssrc/main/ai-vault/runtime-session-scanner.tssrc/main/ai-vault/session-first-user-prompt-read.test.tssrc/main/ai-vault/session-first-user-prompt-read.tssrc/main/ai-vault/session-scanner-accumulator.tssrc/main/ai-vault/session-scanner-first-user-prompt-capture.tssrc/main/ai-vault/session-scanner-first-user-prompt.test.tssrc/main/ai-vault/session-scanner-first-user-prompt.tssrc/main/ai-vault/session-scanner-grok-parser.test.tssrc/main/ai-vault/session-scanner-grok-parser.tssrc/main/ai-vault/session-scanner-grok-user-text.test.tssrc/main/ai-vault/session-scanner-grok-user-text.tssrc/main/ai-vault/session-scanner-injected-title.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite.tssrc/main/ai-vault/session-scanner-preview-window-truncation.test.tssrc/main/ai-vault/session-scanner-primary-parsers.tssrc/main/ai-vault/session-scanner-secondary-parsers.tssrc/main/ai-vault/session-scanner-text-normalization.tssrc/main/ai-vault/session-scanner-types.tssrc/main/ai-vault/session-scanner-values.test.tssrc/main/ai-vault/session-scanner-values.tssrc/main/ai-vault/session-scanner.test.tssrc/main/ipc/ai-vault.tssrc/preload/api-types.tssrc/preload/index.tssrc/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsxsrc/renderer/src/components/right-sidebar/AiVaultSessionRow.tsxsrc/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsxsrc/renderer/src/components/right-sidebar/ai-vault-session-display.test.tssrc/renderer/src/components/right-sidebar/ai-vault-session-display.tssrc/renderer/src/components/right-sidebar/ai-vault-session-row-display.tsxsrc/renderer/src/components/right-sidebar/ai-vault-session-time.tsxsrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.jsonsrc/renderer/src/lib/ai-vault-resume-command.tssrc/renderer/src/web/web-preload-api.tssrc/shared/ai-vault-resume-command.test.tssrc/shared/ai-vault-resume-command.tssrc/shared/ai-vault-session-display.tssrc/shared/ai-vault-types.tssrc/shared/harness-injected-user-turns.test.tssrc/shared/harness-injected-user-turns.ts
|
@coderabbitai[bot] fixed |
|
Tip For best results, initiate chat on the files or code changes.
If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! You are interacting with an AI system. |
…t-prompt-to-agent-session-history-row-wip
- Add 15s timeout to full-prompt load to prevent indefinite loading states - Extract seedFullFirstUserPrompt helper for reuse across parsers - Prevent AI-generated summaries from becoming the copyable first prompt - Fix truncation detection in OpenCode SQLite by probing for N+1 rows - Optimize text bounding to apply safety limit before toLowerCase - Gate synthetic OpenCode path detection on agent type, not just # presence - Add test coverage for remote execution host handling
Clears loadPromiseRef during cleanup to prevent the dedupe handle from causing StrictMode remounts to await stale in-flight requests. Stops loading when session becomes non-loadable mid-request. Adds tests for StrictMode double-invoke resolution and main-process timeout scenarios.
|
@coderabbitai[bot] fixed |
|
Tip For best results, initiate chat on the files or code changes.
You are interacting with an AI system. |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/ai-vault/session-scanner-secondary-parsers.ts (1)
239-263: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winSeed
firstUserPromptfrom the earliest message bymessage.time.created.
consumeOpenCodeMessagesseeds the first prompt from the first directory entry it reads, butreaddirdoes not preserve transcript order. Parse the valid.jsonmessages, sort them bymessage.time.created, seed once from the first user turn, and add a regression test where file order differs from creation order.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ac9ef74c-1e97-44b3-ab71-6045aadfcc8a
📒 Files selected for processing (11)
src/main/ai-vault/session-first-user-prompt-read.test.tssrc/main/ai-vault/session-first-user-prompt-read.tssrc/main/ai-vault/session-scanner-accumulator.tssrc/main/ai-vault/session-scanner-first-user-prompt.tssrc/main/ai-vault/session-scanner-injected-title.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite.tssrc/main/ai-vault/session-scanner-secondary-parsers.tssrc/main/ssh/ssh-connection-utils.tssrc/main/ssh/ssh-connection.test.tssrc/main/ssh/ssh-connection.tssrc/relay/git-handler.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- src/main/ai-vault/session-scanner-first-user-prompt.ts
- src/main/ai-vault/session-first-user-prompt-read.test.ts
- src/main/ai-vault/session-scanner-opencode-sqlite.ts
- src/main/ai-vault/session-scanner-injected-title.test.ts
- src/main/ai-vault/session-first-user-prompt-read.ts
Split secondary-parsers into individual files per agent type (copilot, cursor, hermes, opencode) for improved modularity. Add test coverage for first-user-prompt envelope handling: unwrap user_query tags and reject bare user_info dumps.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7d30646a-239b-4284-9d89-8164dfc09cf2
📒 Files selected for processing (10)
src/main/ai-vault/remote-session-scanner-sources.tssrc/main/ai-vault/session-scanner-agent-parser.tssrc/main/ai-vault/session-scanner-copilot-parser.tssrc/main/ai-vault/session-scanner-cursor-parser.tssrc/main/ai-vault/session-scanner-first-user-prompt.test.tssrc/main/ai-vault/session-scanner-first-user-prompt.tssrc/main/ai-vault/session-scanner-hermes-parser.tssrc/main/ai-vault/session-scanner-opencode-parser.tssrc/main/ai-vault/session-scanner-parse-cache.tssrc/main/ai-vault/session-scanner-secondary-parsers.ts
💤 Files with no reviewable changes (1)
- src/main/ai-vault/session-scanner-secondary-parsers.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/ai-vault/session-scanner-first-user-prompt.ts
Collapse an accidental multi-line regex wrap in ssh-connection-utils that pushed counted lines to 301. Harden the latched-readiness test's ready transition so CI load can re-observe attach after MutationObserver gaps.
Move resolveEffectiveProxy/spawnProxyCommand out of ssh-connection-utils so oxfmt line wrapping cannot push that file over the 300-line lint cap.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 010c8093-9398-4b76-a60f-89c52cbf0384
📒 Files selected for processing (1)
src/renderer/src/components/activity/activity-portal-readiness-loop.react185.test.tsx
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
src/main/ssh/ssh-proxy-command.ts (1)
92-105: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winPropagate backpressure from the proxy's stdout.
onStdoutDataignoresstream.push(data)'s return value. If the consumer reads slower than the proxy writes, data buffers unboundedly on the Duplex instead of pausingproc.stdout.♻️ Proposed fix
const onStdoutData = (data: Buffer): void => { - stream.push(data) + if (!stream.push(data)) { + proc.stdout!.pause() + } } ... const stream = new Duplex({ - read() {}, + read() { + proc.stdout!.resume() + },
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5c1d339b-2448-412a-a633-1fda20abd16e
📒 Files selected for processing (4)
src/main/ssh/ssh-connection-utils.test.tssrc/main/ssh/ssh-connection-utils.tssrc/main/ssh/ssh-connection.tssrc/main/ssh/ssh-proxy-command.ts
💤 Files with no reviewable changes (1)
- src/main/ssh/ssh-connection-utils.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/ssh/ssh-connection.ts
|
@coderabbitai[bot] resolved |
|
✅ Action performedComments resolved. Approval is disabled; enable |
- Add `readOpenCodeMessagesInOrder` to rebuild transcript by timestamp, handling corrupt/partial files gracefully instead of discarding sessions - Extract SSH proxy command tests to dedicated file; add backpressure handling and stderr draining to prevent proxy process stalls - On Windows, reject unsafe characters in ProxyCommand values instead of pretending to escape them; properly format cmd.exe invocation with verbatim arguments - Expand ProxyJump chains into -J plus final hop, mirroring OpenSSH behavior - Decouple portal readiness reapply budget from flip-count budget via explicit constant
* Add first user prompt to AI Vault session history rows Re-parse transcripts on demand to extract and display the untruncated first user prompt for copy/reuse. List scans omit the body (payload/perf); UI loads it when session details expand. Grok sessions extract the typed ask from <user_query> envelope, skipping injected <user_info> bootstrap rows. Supports Claude, Codex, Grok, and OpenCode agents. * fix(ai-vault): split SessionTime out to pass max-lines lint AiVaultSessionDetails exceeded the 400-line oxlint limit after adding first-prompt UI; move SessionTime into its own module. * fix(ai-vault): handle corrupt transcripts and fix OpenCode prompt captur Corrupt transcripts now resolve null instead of rejecting the IPC call, matching behavior for other unavailable cases. OpenCode SQLite parsing now correctly captures all text parts from the earliest user message only, fixing truncation of large prompts and padding of small ones. Add stale-response guard in the UI to prevent late results from overwriting the current session when tabs switch. Consolidate text slicing via `sliceAtCodeUnitLimit` to avoid surrogate-pair splits across all callers. * test(ai-vault): add first-user-prompt UTF-16 safety tests Ensure truncation at safety limits doesn't split UTF-16 surrogate pairs, preventing corruption of astral characters in captured prompts. * fix(ai-vault): key first-prompt-card by session.id Remounting the card on session switches prevents late responses from a previous load from writing stale data into the component's refs. Also improves conversation-turn key stability. * fix(ai-vault): preserve first prompt after preview truncation * refactor(ai-vault): improve first user prompt capture robustness and per - Add 15s timeout to full-prompt load to prevent indefinite loading states - Extract seedFullFirstUserPrompt helper for reuse across parsers - Prevent AI-generated summaries from becoming the copyable first prompt - Fix truncation detection in OpenCode SQLite by probing for N+1 rows - Optimize text bounding to apply safety limit before toLowerCase - Gate synthetic OpenCode path detection on agent type, not just # presence - Add test coverage for remote execution host handling * Fix FirstPromptCard loading state stranded by stale promise reuse Clears loadPromiseRef during cleanup to prevent the dedupe handle from causing StrictMode remounts to await stale in-flight requests. Stops loading when session becomes non-loadable mid-request. Adds tests for StrictMode double-invoke resolution and main-process timeout scenarios. * refactor(ai-vault): split session parsers into modular files Split secondary-parsers into individual files per agent type (copilot, cursor, hermes, opencode) for improved modularity. Add test coverage for first-user-prompt envelope handling: unwrap user_query tags and reject bare user_info dumps. * fix(ci): clear max-lines and flaky portal readiness check Collapse an accidental multi-line regex wrap in ssh-connection-utils that pushed counted lines to 301. Harden the latched-readiness test's ready transition so CI load can re-observe attach after MutationObserver gaps. * fix(ssh): extract proxy command helpers to pass max-lines Move resolveEffectiveProxy/spawnProxyCommand out of ssh-connection-utils so oxfmt line wrapping cannot push that file over the 300-line lint cap. * capture first user prompt by ordering OpenCode messages by creation time - Add `readOpenCodeMessagesInOrder` to rebuild transcript by timestamp, handling corrupt/partial files gracefully instead of discarding sessions - Extract SSH proxy command tests to dedicated file; add backpressure handling and stderr draining to prevent proxy process stalls - On Windows, reject unsafe characters in ProxyCommand values instead of pretending to escape them; properly format cmd.exe invocation with verbatim arguments - Expand ProxyJump chains into -J plus final hop, mirroring OpenSSH behavior - Decouple portal readiness reapply budget from flip-count budget via explicit constant
Summary
Verification
pnpm exec vitest run --config config/vitest.config.ts src/main/ai-vault/session-scanner-preview-window-truncation.test.ts src/renderer/src/components/right-sidebar/ai-vault-session-display.test.ts src/shared/ai-vault-resume-command.test.ts src/shared/ai-vault-session-display.test.tspnpm run typecheckoxlintAll focused tests passed (21 tests).