Skip to content

Implement opt-in session capture: create ai-chat node at PTY session end - #1168

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1125-session-capture
May 18, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1125-session-capture

Conversation

@malibio

@malibio malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator

Closes #1125

Summary

  • SessionCapture ring buffer (max 1 MB) accumulates PTY output per session in packages/agent/src/pty/capture.rs
  • New gRPC RPCs GetCaptureSettings / UpdateCaptureSettings added to settings_service.proto; backed by [capture] section in ~/.nodespace/daemon.toml
  • capture_service::finalize_capture() creates an ai-chat node on session end (metadata, summary, or full transcript per CaptureContentLevel)
  • AgentSessionHandler.launch_session spawns a watcher task that calls finalize_capture after PTY exit
  • Tauri commands get_capture_settings / update_capture_settings proxy the gRPC calls
  • AgentLaunchPanel.svelte: expandable "Session capture" section with enable toggle, content level select, and sync toggle
  • SessionsPanel.svelte: shows "Capture saved" badge on ended sessions when capture is enabled

Test plan

  • Capture settings persist across daemon restarts (check ~/.nodespace/daemon.toml)
  • getCaptureSettings returns correct defaults in browser mode (non-Tauri)
  • Launch panel shows capture settings collapsed by default; expand and toggle works
  • Session ends → "ended" badge + "Capture saved" text appear in sessions panel when capture enabled
  • Capture disabled → no ai-chat node created on session end
  • Unit tests: bun run test -- capture-settings

🤖 Generated with Claude Code

@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a well-structured implementation of opt-in session capture. The core architecture — ring buffer in capture.rs, async watcher task in agent_session_service.rs, fire-and-forget finalization, proto-backed settings — is sound and follows established project patterns. The change is a net improvement and mostly correct. However, there are several issues spanning correctness, a missing acceptance criterion, and a few structural concerns that should be addressed before merge.


Findings

[Critical/Blocker] Invalid status value written to ai-chat node schema

File: packages/daemon/src/services/capture_service.rs:63

capture_service.rs writes "status": "completed" into the ai-chat node properties. The ai-chat schema in packages/core/src/models/core_schemas.rs defines status as a closed enum with only two valid values: "active" and "archived". There is no "completed" value. This is a schema violation that will either cause node creation to fail silently or store a node with an invalid property, breaking any UI that reads the status field.

Fix: Use "status": "archived" (a completed PTY session is analogous to an archived conversation) or add a "completed" variant to the schema's status enum.


[Critical/Blocker] Acceptance criterion not implemented: sync exclusion

File: No file — missing implementation.

Issue #1125 requires: "capture.sync = false (default): sync service excludes nodes with agent_session_id property from sync payloads." No sync service file was modified in this PR. The capture.sync setting is persisted and surfaced in the UI, but the filter that enforces it is absent. This criterion is explicitly listed in the issue and is the privacy-correctness guarantee of the feature. It must be implemented or the criterion must be formally deferred and tracked in a follow-up issue.


[Improvement] pub capture field breaks encapsulation on PtySession

File: packages/agent/src/pty/session.rs:112

pub capture: Arc<Mutex<SessionCapture>>,

PtySession is a public API struct. Exposing capture as a pub field lets any caller mutate or hold the lock arbitrarily. The lock is held across finalize_capture() (an async call doing file I/O and a gRPC create_node call), which will block the reader task from writing new chunks for the duration — acceptable here since the PTY has exited, but fragile as an invariant to maintain. Prefer a pub fn snapshot_capture(&self) -> SessionCapture or similar accessor that takes a clone/snapshot of the buffer contents under a brief lock, rather than exposing the live Arc<Mutex<>>.


[Improvement] Config path construction duplicated across three call sites

Files: packages/daemon/src/main.rs:217, packages/desktop-app/src-tauri/src/services/grpc_client.rs:115, and packages/daemon/src/services/settings_service.rs:112

The ~/.nodespace/daemon.toml path is constructed three times with slightly inconsistent error handling: settings_service.rs correctly returns an error when $HOME is unset; main.rs and grpc_client.rs both use unwrap_or_default(), silently producing a path of .nodespace/daemon.toml relative to the process working directory. Extract this into a shared helper (e.g., nodespace_config_path() -> Result<PathBuf>) used everywhere.


[Improvement] read_capture_settings re-reads the TOML file on every finalize_capture call

File: packages/daemon/src/services/capture_service.rs:38

finalize_capture calls read_capture_settings, which performs a fresh tokio::fs::read_to_string + TOML parse on every session end. The SettingsServiceImpl already owns the file path and a write serialization mutex; having capture_service do its own independent file reads is a layering violation and adds file I/O on the hot path of session teardown. Pass a CaptureConfig snapshot into finalize_capture (computed at the start of the watcher task from the daemon's in-memory config), or accept a &CaptureConfig directly.


[Improvement] Capture watcher task is only registered at launch_session time

File: packages/daemon/src/services/agent_session_service.rs:113

Sessions that were already running when the daemon starts (or when grpc_client.rs initializes the embedded daemon) will never have a capture watcher spawned. In the current architecture this is unlikely to matter in practice, but it is an invisible behavioral gap. Add a comment documenting this limitation (e.g., "Capture is only finalized for sessions launched via this handler; sessions inherited from a previous daemon instance are not captured.").


[Improvement] capturedNodeId is always null — "View captured session →" link is dead

File: packages/desktop-app/src/lib/components/agent/sessions-panel.svelte:94

{ sessionId, agentType, capturedNodeId: null, endedAt: Date.now() }

The capturedNodeId field exists in the EndedSession interface but is always set to null. The issue acceptance criterion states "a link to the created ai-chat node is shown in the sessions panel". The UI renders a "View captured session →" button only when capturedNodeId is non-null, so it never renders. The backend creates the node asynchronously — the frontend has no channel to receive the resulting node ID. This is either a missing Tauri event (e.g., pty-capture-complete-{sessionId} carrying the node ID) or the acceptance criterion is not met. If the link is deferred, the dead code path should be removed and tracked separately.


[Improvement] closedListeners Map leaks if component is destroyed while sessions are active

File: packages/desktop-app/src/lib/components/agent/sessions-panel.svelte:46

const closedListeners = new Map<string, () => void>();

There is no onDestroy cleanup that calls each stored unlisten() function. If the SessionsPanel component is unmounted while sessions are still active (e.g., navigating away), the Tauri event listeners will remain registered. Use onDestroy to iterate the map and call each unlisten callback, or return a cleanup function from the $effect.


[Improvement] Missing Rust unit tests for finalize_capture

File: packages/daemon/src/services/capture_service.rs

Issue #1125 explicitly requires:

  • Unit test: metadata_only capture creates a node with correct fields and no transcript
  • Unit test: full capture creates a node with the full output buffer
  • Unit test: capture disabled → no node created

These tests exist for the ring buffer (capture.rs has solid test coverage) and for the frontend mock path (capture-settings.test.ts), but capture_service.rs has zero #[cfg(test)] coverage. The most important behavioral assertion — that finalize_capture correctly assembles the node payload for each content level — is untested at the Rust layer.


[Improvement] agent_session_id property has no namespace prefix

File: packages/daemon/src/services/capture_service.rs:60

Per CLAUDE.md node schema rules, user/system properties stored on core node types should use namespace prefixes (custom:, org:, plugin:) to avoid conflicts with future core properties. agent_session_id, transcript, summary, started_at, ended_at, exit_code, and agent_type are being stored without prefixes on the ai-chat schema. The issue spec itself uses unprefixed names; if these properties are meant to be promoted to the ai-chat core schema, they should be added there explicitly (with proper SchemaField entries) rather than written as freeform JSON. Either add the fields to the schema or use prefixed names.


Nits

  • packages/daemon/src/services/agent_session_service.rs:113: The double self.manager.get(&id) calls (lines 82 and 113) introduce a narrow TOCTOU gap — the session is fetched twice separately. This is harmless in practice but could be consolidated by reusing the first lookup.

  • packages/desktop-app/src/lib/services/tauri-commands.ts: The non-Tauri mock for updateCaptureSettings constructs a new object each call without preserving state, so successive calls don't accumulate — this is fine for the mock fallback but worth a comment to set expectations.

  • packages/agent/src/pty/capture.rs:SUMMARY_MAX_BYTES: The constant is named SUMMARY_MAX_BYTES but the issue spec says "first 500 chars". For ASCII content these are equivalent; for multi-byte UTF-8 they differ. The current implementation truncates at a char boundary after 500 bytes, which is correct and safe — a brief comment clarifying "500 bytes, not 500 characters" would prevent future confusion.


Acceptance Criteria Status

Criterion Status
capture.enabled, capture.sync, capture.content settings Done
Settings readable/writable via gRPC Done
Settings UI (toggle + content level selector) Done
capture.enabled = false → no node created Done
metadata_only → ai-chat node with correct metadata Done (schema violation in status value)
summary and full content levels Done
ai-chat node via NodeService.CreateNode Done
agent_session_id stored as node property Done (namespace prefix concern)
Capture after PTY exit, non-blocking Done
Failed capture logged, not surfaced to user Done
capture.sync = false → excluded from sync Missing
AgentLaunchPanel.svelte capture settings UI Done
Link to captured ai-chat node in sessions panel Partial (capturedNodeId always null)
Unit tests: metadata_only, full, disabled Partial (ring buffer tested; finalize_capture not tested)
bun run test:all passes Not verified in PR
bun run quality:fix passes Not verified in PR

🤖 Generated with Claude Code

Michael Libio and others added 2 commits May 19, 2026 00:18
…end (closes #1125)

- Add SessionCapture ring buffer (max 1MB) to PTY sessions via capture.rs
- Extend settings_service.proto with GetCaptureSettings / UpdateCaptureSettings RPCs
- Add CaptureConfig + CaptureContentSetting to daemon config (TOML-persisted)
- Add capture_service: finalize_capture() creates ai-chat node on session end
- Wire capture watcher task in AgentSessionHandler.launch_session
- Add get_capture_settings / update_capture_settings Tauri commands
- AgentLaunchPanel.svelte: capture settings UI (enable, content level, sync toggle)
- SessionsPanel.svelte: show "Capture saved" badge on session end when capture enabled
- Frontend CaptureSettings API in tauri-commands.ts with non-Tauri mock fallback
- Unit tests for capture ring buffer and frontend settings API

Co-Authored-By: Claude <[email protected]>
…t API, tests, cleanup

- Fix status field: "completed" → "archived" (matches ai-chat schema closed enum)
- Add capture: namespace prefix to all agent-session-specific properties
- Refactor: extract build_node_payload() for testability without NodeService
- Add 5 Rust unit tests covering content-level gating, status, namespace enforcement
- Add snapshot_capture() accessor to PtySession; make SessionCapture Clone
- Read CaptureConfig once at session-launch time, pass snapshot to finalize_capture
- Add onDestroy cleanup of Tauri event listeners in SessionsPanel to prevent leaks

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the worktree-issue-1125-session-capture branch from 7fa5076 to 80f80ef Compare May 18, 2026 22:33
@malibio
malibio merged commit 19a5745 into main May 18, 2026
@malibio
malibio deleted the worktree-issue-1125-session-capture branch May 18, 2026 22:35
malibio added a commit that referenced this pull request Jun 22, 2026
…end (#1168)

* Implement opt-in session capture: create ai-chat node at PTY session end (closes #1125)

- Add SessionCapture ring buffer (max 1MB) to PTY sessions via capture.rs
- Extend settings_service.proto with GetCaptureSettings / UpdateCaptureSettings RPCs
- Add CaptureConfig + CaptureContentSetting to daemon config (TOML-persisted)
- Add capture_service: finalize_capture() creates ai-chat node on session end
- Wire capture watcher task in AgentSessionHandler.launch_session
- Add get_capture_settings / update_capture_settings Tauri commands
- AgentLaunchPanel.svelte: capture settings UI (enable, content level, sync toggle)
- SessionsPanel.svelte: show "Capture saved" badge on session end when capture enabled
- Frontend CaptureSettings API in tauri-commands.ts with non-Tauri mock fallback
- Unit tests for capture ring buffer and frontend settings API

Co-Authored-By: Claude <[email protected]>

* Address review findings: status=archived, namespace prefixes, snapshot API, tests, cleanup

- Fix status field: "completed" → "archived" (matches ai-chat schema closed enum)
- Add capture: namespace prefix to all agent-session-specific properties
- Refactor: extract build_node_payload() for testability without NodeService
- Add 5 Rust unit tests covering content-level gating, status, namespace enforcement
- Add snapshot_capture() accessor to PtySession; make SessionCapture Clone
- Read CaptureConfig once at session-launch time, pass snapshot to finalize_capture
- Add onDestroy cleanup of Tauri event listeners in SessionsPanel to prevent leaks

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
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.

Implement opt-in session capture: create ai-chat node at PTY session end

1 participant