Skip to content

Add first user prompt to AI Vault session history row - #12006

Merged
AmethystLiang merged 5 commits into
mainfrom
add-first-prompt-to-agent-session-history-row
Aug 2, 2026
Merged

AmethystLiang merged 5 commits into
mainfrom
add-first-prompt-to-agent-session-history-row

Conversation

@AmethystLiang

Copy link
Copy Markdown
Contributor

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

  • Backend: Session scanner now captures firstUserPrompt separately from preview/title via new SessionAccumulator field and AiVaultFirstUserPromptArgs IPC handler
  • Capture modes: List scans omit firstUserPrompt (payload/perf); on-demand copy re-parses one transcript under full capture via AsyncLocalStorage
  • Agent support: Handles Claude (claude), Codex (codex), OpenCode (opencode), and Grok (grok) formats with format-specific text extraction
  • Filtering: Skips harness-injected turns and Grok bootstrap <user_info> rows; extracts real ask from <user_query> envelope
  • UI: New FirstPromptCard component in session details with async load and copy-to-clipboard button with toast feedback
  • i18n: Added translations for en/es/ja/ko/zh

Testing

  • src/main/ai-vault/session-first-user-prompt-read.test.ts — full-text reads for Claude and Codex formats; meta turn filtering
  • src/main/ai-vault/session-scanner-grok-parser.test.ts — <user_query> unwrapping under full capture mode
  • src/main/ai-vault/session-scanner-grok-user-text.test.ts — Grok envelope handling and bootstrap context rejection
  • src/renderer/src/components/right-sidebar/ai-vault-session-display.test.ts — preview fallback when firstUserPrompt absent
  • Existing tests updated to verify firstUserPrompt remains absent from list scans

Cross-platform notes

  • All changes are platform-agnostic (no OS-specific shortcuts, paths, or behavior)
  • SSH hosts resolve to null (transcript bodies live on session host only)
  • Folder workspaces supported via same session-scanner infrastructure

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-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This 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 AsyncLocalStorage-scoped "full capture" mode fetches the untruncated text only when the user opens session details.

  • Backend: SessionAccumulator gains a firstUserPrompt field populated only during full-capture re-parses; agent-specific parsers (Claude, Codex, OpenCode SQLite/JSON, Grok) each have tailored extraction paths with harness-injection filtering and Grok <user_query> envelope unwrapping.
  • OpenCode SQLite: uses a dedicated SQL query ordered by time_created/rowid to reliably fetch the chronologically earliest user message, correctly bypassing the newest-N preview window.
  • UI: new FirstPromptCard uses a generation counter to discard stale IPC responses after session switches; the session row's drag handle is narrowed to the title element to allow text selection in the expanded details area.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

Reviews (4): Last reviewed commit: "fix(ai-vault): key first-prompt-card by ..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fc60e9c0-c469-4906-b136-77b74f17f6bb

📥 Commits

Reviewing files that changed from the base of the PR and between 7515b8e and 59635ac.

📒 Files selected for processing (2)
  • src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx
  • src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx

📝 Walkthrough

Walkthrough

AI 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the feature and tests, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing required sections, document screenshot status, complete the test checklist, and include AI review and security audit findings.
Docstring Coverage ⚠️ Warning Docstring coverage is 20.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding the first user prompt to AI Vault session history.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

@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: 3

🧹 Nitpick comments (3)
src/main/ai-vault/session-scanner-grok-parser.ts (1)

84-89: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Redundant duplicate extraction call.

extractGrokDisplayUserText is a direct alias of extractGrokFirstUserPromptText (see session-scanner-grok-user-text.ts lines 35-37). Calling both on the same record.content re-runs identical envelope-stripping and bootstrap-detection work twice per user turn, and previewSource = displayBody ?? firstPromptBody always resolves to firstPromptBody. 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))
           : null
src/main/ai-vault/session-scanner-grok-parser.test.ts (1)

23-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tautological assertion provides no test coverage.

trimCalls is 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 on trimCalls, or toBeGreaterThan(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 win

Add 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 readAiVaultFirstUserPrompt resolves { prompt: null } instead of rejecting. Add this case once the missing try/catch in session-first-user-prompt-read.ts is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1542082 and 5a27499.

📒 Files selected for processing (38)
  • src/main/ai-vault/runtime-session-scanner.ts
  • src/main/ai-vault/session-first-user-prompt-read.test.ts
  • src/main/ai-vault/session-first-user-prompt-read.ts
  • src/main/ai-vault/session-scanner-accumulator.ts
  • src/main/ai-vault/session-scanner-first-user-prompt-capture.ts
  • src/main/ai-vault/session-scanner-first-user-prompt.ts
  • src/main/ai-vault/session-scanner-grok-parser.test.ts
  • src/main/ai-vault/session-scanner-grok-parser.ts
  • src/main/ai-vault/session-scanner-grok-user-text.test.ts
  • src/main/ai-vault/session-scanner-grok-user-text.ts
  • src/main/ai-vault/session-scanner-injected-title.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite.ts
  • src/main/ai-vault/session-scanner-primary-parsers.ts
  • src/main/ai-vault/session-scanner-secondary-parsers.ts
  • src/main/ai-vault/session-scanner-text-normalization.ts
  • src/main/ai-vault/session-scanner-types.ts
  • src/main/ai-vault/session-scanner-values.test.ts
  • src/main/ai-vault/session-scanner-values.ts
  • src/main/ai-vault/session-scanner.test.ts
  • src/main/ipc/ai-vault.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx
  • src/renderer/src/components/right-sidebar/AiVaultSessionRow.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-session-display.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-display.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-row-display.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/ai-vault-session-display.ts
  • src/shared/ai-vault-types.ts
  • src/shared/harness-injected-user-turns.test.ts
  • src/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.

@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.

🧹 Nitpick comments (1)
src/renderer/src/components/right-sidebar/ai-vault-session-time.tsx (1)

5-30: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Relative time text goes stale without a refresh.

formatTimeAgo computes the elapsed-time label once, at render time. If SessionTime stays 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 useState tick updated on a setInterval, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a27499 and af184e3.

📒 Files selected for processing (14)
  • src/main/ai-vault/session-first-user-prompt-read.test.ts
  • src/main/ai-vault/session-first-user-prompt-read.ts
  • src/main/ai-vault/session-scanner-first-user-prompt.ts
  • src/main/ai-vault/session-scanner-grok-parser.test.ts
  • src/main/ai-vault/session-scanner-grok-parser.ts
  • src/main/ai-vault/session-scanner-grok-user-text.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite.test.ts
  • src/main/ai-vault/session-scanner-opencode-sqlite.ts
  • src/main/ai-vault/session-scanner-text-normalization.ts
  • src/main/ai-vault/session-scanner-values.ts
  • src/renderer/src/components/right-sidebar/AiVaultSessionDetails.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-first-prompt-card.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-session-row-display.tsx
  • src/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.

@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.

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 win

Restore the trim spy when extraction fails.

If extractGrokContentText throws, trimSpy.mockRestore() is skipped and the file-level afterEach only removes temp roots. Later tests can run with String.prototype.trim still mocked. Wrap the extraction in try/finally, or restore mocks in afterEach.

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 win

Assert the exact truncated prefix.

toHaveLength and endsWith do not prove that the retained prefix is unchanged. A corrupted string with the same length and an a suffix 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

📥 Commits

Reviewing files that changed from the base of the PR and between af184e3 and 7515b8e.

📒 Files selected for processing (2)
  • src/main/ai-vault/session-scanner-first-user-prompt.test.ts
  • src/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.
@AmethystLiang
AmethystLiang merged commit dbfffa6 into main Aug 2, 2026
43 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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.
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.

1 participant