Repository navigation
Add first user prompt to AI Vault session history row - #12006
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.
Greptile SummaryThis PR adds on-demand "first user prompt" capture for AI Vault sessions, letting users copy their original request from the session history panel. List scans are kept payload-light by omitting the field; a dedicated re-parse under
Confidence Score: 5/5Safe to merge — the change is additive, well-scoped to the new copy path, and list-scan performance is unaffected by design. The AsyncLocalStorage scoping correctly isolates full-capture behavior to the single on-demand re-parse. Each agent's extraction path is tested, harness-injection filtering is guarded on both ends, and the generation-counter fix prevents stale IPC writes after session switches. The one edge case — OpenCode JSON's seeding path could fall through to a summary string rather than actual message content — only fires when a user message has no extractable body, which is uncommon in practice and produces a benign degradation rather than incorrect data. Files Needing Attention: src/main/ai-vault/session-scanner-secondary-parsers.ts — consumeOpenCodeMessages lacks the explicit seedFirstUserPrompt: false guard that the SQLite path uses, creating a minor inconsistency when message content is absent.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx | New FirstPromptCard component with generation-counter stale-response guard, async load-then-copy, and toast feedback. Previously flagged stale-IPC and preview-fallback issues are addressed by key remounting and the generationRef pattern. |
| src/main/ai-vault/session-first-user-prompt-read.ts | IPC handler re-parses one transcript under full-capture mode via AsyncLocalStorage; remote/SSH hosts correctly return null; parse errors are caught and resolve to null. |
| src/main/ai-vault/session-scanner-first-user-prompt.ts | Extraction and normalization logic for the full first-user prompt; correctly handles string, single-block, and array content; applies harness filtering and Grok envelope stripping; 256 KB safety cap with surrogate-safe slicing. |
| src/main/ai-vault/session-scanner-grok-user-text.ts | New Grok user-turn text helpers; correctly identifies and strips user_info bootstrap rows, unwraps user_query envelope (handles missing closing tag), and guards against git_status-padded bootstrap rows. |
| src/main/ai-vault/session-scanner-accumulator.ts | firstUserPrompt field added to SessionAccumulator; seeding is correctly gated on shouldCaptureFullFirstUserPrompt() and the !accumulator.firstUserPrompt guard so only the first non-injected user turn wins. |
| src/main/ai-vault/session-scanner-opencode-sqlite.ts | Dedicated readFirstUserPromptFromOpenCodeDb SQL query explicitly orders by time_created/rowid to fetch the chronologically earliest user message; preview messages pass seedFirstUserPrompt: false to prevent double-seeding. |
| src/main/ai-vault/session-scanner-secondary-parsers.ts | consumeOpenCodeMessages switched from extractPreviewContentText to extractFullFirstUserPromptText; missing seedFirstUserPrompt: false means summary fallback text could seed firstUserPrompt when message content is null — see inline comment. |
| src/shared/ai-vault-session-display.ts | New sessionFirstPrompt helper iterates previewMessages for a placeholder; previewMessages is the last-5-message window, so the returned text may not be the chronological first prompt (noted in previous review thread). |
Sequence Diagram
sequenceDiagram
participant UI as FirstPromptCard
participant IPC as aiVault IPC
participant Read as session-first-user-prompt-read
participant ALS as AsyncLocalStorage
participant Parser as Agent Parser
participant Acc as SessionAccumulator
UI->>IPC: getFirstUserPrompt(agent, filePath, sessionId)
IPC->>Read: handleAiVaultGetFirstUserPrompt(args)
Read->>ALS: withFullFirstUserPromptCapture(fn)
ALS-->>Parser: run fn with capture mode full
Parser->>Acc: addPreviewContent or addPreviewMessage
Note over Acc: shouldCaptureFullFirstUserPrompt true seeds firstUserPrompt on first real user turn
Acc-->>Parser: accumulator.firstUserPrompt set
Parser-->>Read: AiVaultSession with firstUserPrompt
Read-->>IPC: prompt from session.firstUserPrompt
IPC-->>UI: AiVaultFirstUserPromptResult
UI->>UI: setFullText then copy to clipboard
Reviews (4): Last reviewed commit: "fix(ai-vault): key first-prompt-card by ..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAI Vault sessions now support full first-user-prompt extraction while excluding injected and metadata turns. Scanners store the prompt when full capture is enabled. A new IPC and preload API retrieves it on demand. The renderer displays, loads, and copies the prompt with localized states. Grok, OpenCode, Claude, and Codex parsing include prompt-specific handling and test coverage. 🚥 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: 3
🧹 Nitpick comments (3)
src/main/ai-vault/session-scanner-grok-parser.ts (1)
84-89: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRedundant duplicate extraction call.
extractGrokDisplayUserTextis a direct alias ofextractGrokFirstUserPromptText(seesession-scanner-grok-user-text.tslines 35-37). Calling both on the samerecord.contentre-runs identical envelope-stripping and bootstrap-detection work twice per user turn, andpreviewSource = displayBody ?? firstPromptBodyalways resolves tofirstPromptBody. Compute the value once and reuse it.♻️ Proposed fix to remove the duplicate call
if (role === 'user') { // Why: first-prompt copy must be the typed ask inside <user_query>, never // the injected <user_info> bootstrap row. const firstPromptBody = extractGrokFirstUserPromptText(record.content) - const displayBody = extractGrokDisplayUserText(record.content) - const previewSource = displayBody ?? firstPromptBody - const text = previewSource - ? normalizePreviewText(capGrokPreviewSource(previewSource)) + const text = firstPromptBody + ? normalizePreviewText(capGrokPreviewSource(firstPromptBody)) : nullsrc/main/ai-vault/session-scanner-grok-parser.test.ts (1)
23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTautological assertion provides no test coverage.
trimCallsis a call count, which can never be negative.expect(trimCalls).toBeGreaterThanOrEqual(0)always passes, so it doesn't verify the "cheap" claim in the comment above it. Either remove the assertion or replace it with a meaningful bound (for example, an upper limit ontrimCalls, ortoBeGreaterThan(0)to confirm the expected.trim()call actually happens).src/main/ai-vault/session-first-user-prompt-read.test.ts (1)
1-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test for a corrupted/unparsable transcript.
The current tests cover valid Claude and Codex transcripts and meta-turn filtering. None of them write a malformed JSONL file and assert that
readAiVaultFirstUserPromptresolves{ prompt: null }instead of rejecting. Add this case once the missing try/catch insession-first-user-prompt-read.tsis fixed, to lock in the graceful-fallback behavior for corrupted transcripts.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 21407130-0c7c-4251-825a-5e69fdb3e592
📒 Files selected for processing (38)
src/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.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.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/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/web/web-preload-api.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
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/right-sidebar/ai-vault-session-time.tsx (1)
5-30: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winRelative time text goes stale without a refresh.
formatTimeAgocomputes the elapsed-time label once, at render time. IfSessionTimestays mounted (for example in a session list row or detail panel) without an unrelated re-render, the label stays fixed (for example "Just now") even as real time passes.Add a periodic re-render, for example a
useStatetick updated on asetInterval, so the label advances without requiring an external re-render trigger.♻️ Proposed fix to keep the relative time current
-import type React from 'react' +import { useEffect, useState } from 'react' +import type React from 'react' import { cn } from '`@/lib/utils`' import { translate } from '`@/i18n/i18n`' export function SessionTime({ value, className }: { value: string className?: string }): React.JSX.Element { const timestamp = Date.parse(value) + const [, forceTick] = useState(0) + useEffect(() => { + if (!Number.isFinite(timestamp)) { + return + } + const id = setInterval(() => forceTick((n) => n + 1), 30_000) + return () => clearInterval(id) + }, [timestamp]) if (!Number.isFinite(timestamp)) {Also applies to: 32-74
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0c70d261-5bd1-4544-9dce-1d9e79779c2a
📒 Files selected for processing (14)
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-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.tssrc/main/ai-vault/session-scanner-opencode-sqlite.test.tssrc/main/ai-vault/session-scanner-opencode-sqlite.tssrc/main/ai-vault/session-scanner-text-normalization.tssrc/main/ai-vault/session-scanner-values.tssrc/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsxsrc/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsxsrc/renderer/src/components/right-sidebar/ai-vault-session-row-display.tsxsrc/renderer/src/components/right-sidebar/ai-vault-session-time.tsx
💤 Files with no reviewable changes (2)
- src/main/ai-vault/session-scanner-grok-user-text.ts
- src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx
🚧 Files skipped from review as they are similar to previous changes (8)
- src/main/ai-vault/session-scanner-grok-parser.test.ts
- src/main/ai-vault/session-scanner-values.ts
- src/main/ai-vault/session-scanner-grok-parser.ts
- src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx
- src/main/ai-vault/session-first-user-prompt-read.ts
- src/renderer/src/components/right-sidebar/ai-vault-session-row-display.tsx
- src/main/ai-vault/session-scanner-first-user-prompt.ts
- src/main/ai-vault/session-scanner-text-normalization.ts
Ensure truncation at safety limits doesn't split UTF-16 surrogate pairs, preventing corruption of astral characters in captured prompts.
There was a problem hiding this comment.
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-grok-parser.test.ts (1)
17-23: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRestore the
trimspy when extraction fails.If
extractGrokContentTextthrows,trimSpy.mockRestore()is skipped and the file-levelafterEachonly removes temp roots. Later tests can run withString.prototype.trimstill mocked. Wrap the extraction intry/finally, or restore mocks inafterEach.Proposed cleanup
- const result = extractGrokContentText( - `<USER_INFO>context</USER_INFO><USER_QUERY>\n${'Grok prompt '.repeat(400)}</USER_QUERY>` - ) - const trimCalls = trimSpy.mock.calls.length - trimSpy.mockRestore() + let result: string | null + let trimCalls = 0 + try { + result = extractGrokContentText( + `<USER_INFO>context</USER_INFO><USER_QUERY>\n${'Grok prompt '.repeat(400)}</USER_QUERY>` + ) + trimCalls = trimSpy.mock.calls.length + } finally { + trimSpy.mockRestore() + }
🧹 Nitpick comments (1)
src/main/ai-vault/session-scanner-first-user-prompt.test.ts (1)
8-13: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAssert the exact truncated prefix.
toHaveLengthandendsWithdo not prove that the retained prefix is unchanged. A corrupted string with the same length and anasuffix could pass. Assert the expected prefix directly.Proposed test assertion
- expect(result).toHaveLength(SAFETY_LIMIT - 1) - expect(result?.endsWith('a')).toBe(true) + expect(result).toBe('a'.repeat(SAFETY_LIMIT - 1))
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: aa75559e-c2c7-4fa4-b368-c9080bfda40e
📒 Files selected for processing (2)
src/main/ai-vault/session-scanner-first-user-prompt.test.tssrc/main/ai-vault/session-scanner-grok-parser.test.ts
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.
* 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.
Summary
Capture and display the first user prompt from AI Vault sessions, enabling users to copy their original request for reuse. On-demand re-parsing loads the full untruncated text without impacting list-scan performance.
Changes
firstUserPromptseparately from preview/title via newSessionAccumulatorfield andAiVaultFirstUserPromptArgsIPC handlerfirstUserPrompt(payload/perf); on-demand copy re-parses one transcript under full capture viaAsyncLocalStorage<user_info>rows; extracts real ask from<user_query>envelopeFirstPromptCardcomponent in session details with async load and copy-to-clipboard button with toast feedbackTesting
src/main/ai-vault/session-first-user-prompt-read.test.ts— full-text reads for Claude and Codex formats; meta turn filteringsrc/main/ai-vault/session-scanner-grok-parser.test.ts—<user_query>unwrapping under full capture modesrc/main/ai-vault/session-scanner-grok-user-text.test.ts— Grok envelope handling and bootstrap context rejectionsrc/renderer/src/components/right-sidebar/ai-vault-session-display.test.ts— preview fallback whenfirstUserPromptabsentfirstUserPromptremains absent from list scansCross-platform notes