Skip to content

fix: resolve Issue #56 - fix stack overflow on large session files - #76

Closed
caiyongtian wants to merge 1 commit into
agegr:mainfrom
caiyongtian:fix-issue-56
Closed

caiyongtian wants to merge 1 commit into
agegr:mainfrom
caiyongtian:fix-issue-56

Conversation

@caiyongtian

Copy link
Copy Markdown

Problem

Accessing sessions with large message history (e.g. 1068+ messages) caused HTTP 500 errors due to RangeError: Maximum call stack size exceeded during JSON serialization.

Root Cause

  • Massive session objects from buildSessionContext could not be serialized by NextResponse.json
  • No error handling for corrupted session files
  • No fallback scanning when SessionManager fails
  • Deep agent state objects caused additional serialization issues

Solution

1. lib/session-reader.ts

  • Added 5-second TTL cache for listAllSessions() to avoid repeated expensive scans
  • Implemented safeManualScan() - async fallback scanner using fs/promises
    • Reads only session headers (not full message history)
    • Prevents symlink loops with visitedDirs tracking
    • Non-blocking: runs asynchronously to not block the event loop
  • Added sessions cache integration to resolveSessionPath()

2. app/api/sessions/[id]/route.ts

  • Granular try-catch blocks for: SessionManager.open, getEntries, getTree, getLeafId, getHeader, buildSessionContext, getSessionName, getRpcSession
  • Message truncation: sessions with >500 messages are truncated to last 500
  • Serialization safety net: pre-checks JSON.stringify, falls back to minimal response (empty tree, last 50 messages) if serialization fails
  • Simplified agentState extraction: only includes isStreaming, isCompacting, contextUsage, systemPrompt, thinkingLevel (primitive-safe)
  • Better error responses with details and stack traces

3. next.config.ts

  • Added '127.0.0.1' and 'localhost' to allowedDevOrigins to fix HMR WebSocket errors

Testing

  • Verified GET /api/sessions/019eb1da-0e62-775b-a744-520fb1da496d (1068 messages) now returns 200 with truncated data instead of 500 error
  • Verified GET /api/sessions works correctly with caching
  • Verified GET /api/sessions/:id?includeState works with simplified state

### Problem
Accessing sessions with large message history (e.g. 1068+ messages) caused HTTP 500 errors
due to RangeError: Maximum call stack size exceeded during JSON serialization.

### Root Cause
- Massive session objects from buildSessionContext could not be serialized by NextResponse.json
- No error handling for corrupted session files
- No fallback scanning when SessionManager fails
- Deep agent state objects caused additional serialization issues

### Solution

#### 1. lib/session-reader.ts
- Added 5-second TTL cache for listAllSessions() to avoid repeated expensive scans
- Implemented safeManualScan() - async fallback scanner using fs/promises
  - Reads only session headers (not full message history)
  - Prevents symlink loops with visitedDirs tracking
  - Non-blocking: runs asynchronously to not block the event loop
- Added sessions cache integration to resolveSessionPath()

#### 2. app/api/sessions/[id]/route.ts
- Granular try-catch blocks for: SessionManager.open, getEntries, getTree,
  getLeafId, getHeader, buildSessionContext, getSessionName, getRpcSession
- Message truncation: sessions with >500 messages are truncated to last 500
- Serialization safety net: pre-checks JSON.stringify, falls back to minimal
  response (empty tree, last 50 messages) if serialization fails
- Simplified agentState extraction: only includes isStreaming, isCompacting,
  contextUsage, systemPrompt, thinkingLevel (primitive-safe)
- Better error responses with details and stack traces

#### 3. next.config.ts
- Added '127.0.0.1' and 'localhost' to allowedDevOrigins to fix HMR WebSocket errors

### Testing
- Verified GET /api/sessions/019eb1da-0e62-775b-a744-520fb1da496d (1068 messages)
  now returns 200 with truncated data instead of 500 error
- Verified GET /api/sessions works correctly with caching
- Verified GET /api/sessions/:id?includeState works with simplified state
cnbattle added a commit to cnbattle/pi-web that referenced this pull request Jun 23, 2026
…upstream

PR agegr#83: fix extension/package tools available in pi-web new sessions
PR agegr#80: load extension models in web model selector
PR agegr#78: add ToolsConfig panel with individual tool toggles
PR agegr#65: add scroll-to-bottom control for chat sessions
PR agegr#75: add rehype-raw plugin to render HTML tables in markdown
PR agegr#76: fix stack overflow on large session files (+TTL cache)
@agegr

agegr commented Jun 23, 2026

Copy link
Copy Markdown
Owner

#85

@agegr agegr closed this Jun 23, 2026
c-with pushed a commit to c-with/pi-web that referenced this pull request Sep 30, 2026
PI WEB only supports globally configured providers (Pi built-ins,
agent-dir models.json, environment credentials). A daemon-wide shim on
the shared ModelRuntime swallows extension registerProvider calls and
makes unregisterProvider a no-op, so one workspace's extensions can no
longer corrupt the provider set of concurrent sessions (issue agegr#76).

Rejections during a services load surface as session warnings through
the existing diagnostics pipeline; late registrations from session
event handlers broadcast a notification to active sessions. Everything
else extensions register keeps working.

Requires manual restart of pi-web-sessiond.service (daemon wiring changed).
c-with pushed a commit to c-with/pi-web that referenced this pull request Sep 30, 2026
Relaxes the provider policy from 'global config only' to 'global sources':
providers registered by agent-dir (global) extensions are learned once at
daemon startup and allowed on the shared runtime; project-extension
registrations are still rejected with a session warning. Global extensions
load identically for every session, so their providers are daemon-consistent
and cannot leak project state (agegr#76).

- Shim now allows allowlisted ids through and also covers Pi 0.81's native
  provider path (registerNativeProvider), closing a bypass.
- Startup learning step loads only global extensions against a scratch cwd
  and diffs the runtime's registered provider ids.
- Bumps @earendil-works/* dev/peer ranges to >=0.81.1 <0.82; adapts to the
  Agent.streamFn -> streamFunction rename.
- Docs, changeset, unit and acceptance tests updated (global-extension allow
  path, late re-registration a la pi-tensorx, native provider rule).
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.

2 participants