-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(openclaw): load chat history on agent chat page #790
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shivammittal274
wants to merge
1
commit into
dev
Choose a base branch
from
feat/openclaw-chat-history
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+449
−8
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
|
|
@@ -20,9 +20,73 @@ import { | |||||||
| OpenClawInvalidAgentNameError, | ||||||||
| OpenClawProtectedAgentError, | ||||||||
| } from '../services/openclaw/errors' | ||||||||
| import type { OpenClawChatMessage } from '../services/openclaw/openclaw-cli-client' | ||||||||
| import { isUnsupportedOpenClawProviderError } from '../services/openclaw/openclaw-provider-map' | ||||||||
| import { getOpenClawService } from '../services/openclaw/openclaw-service' | ||||||||
|
|
||||||||
| /** | ||||||||
| * Filter non-user-facing messages from chat.history. | ||||||||
| * | ||||||||
| * OpenClaw's session history contains three kinds of noise: | ||||||||
| * | ||||||||
| * 1. Context replays — When a new message arrives in an existing session, | ||||||||
| * OpenClaw bundles the entire prior conversation into a single user | ||||||||
| * message prefixed with "[Chat messages since your last reply]". | ||||||||
| * This is internal context for the model, not user input. | ||||||||
| * | ||||||||
| * 2. System events — Cron/heartbeat triggers formatted as user messages | ||||||||
| * starting with "System: [timestamp]" and containing | ||||||||
| * "Handle this reminder internally". | ||||||||
| * | ||||||||
| * 3. Heartbeat responses — Assistant messages that are just "HEARTBEAT_OK", | ||||||||
| * which is OpenClaw's standard heartbeat acknowledgment token. | ||||||||
| */ | ||||||||
| function filterSystemMessages( | ||||||||
| messages: OpenClawChatMessage[], | ||||||||
| ): OpenClawChatMessage[] { | ||||||||
| const result: OpenClawChatMessage[] = [] | ||||||||
|
|
||||||||
| for (const msg of messages) { | ||||||||
| const text = msg.content | ||||||||
| .filter((b) => b.type === 'text') | ||||||||
| .map((b) => b.text ?? '') | ||||||||
| .join('') | ||||||||
| .trim() | ||||||||
|
|
||||||||
| // Skip heartbeat responses | ||||||||
| if (msg.role === 'assistant' && text.startsWith('HEARTBEAT')) continue | ||||||||
|
|
||||||||
| // Skip system event triggers (cron/heartbeat) | ||||||||
| if (msg.role === 'user' && text.includes('Handle this reminder internally')) | ||||||||
| continue | ||||||||
|
|
||||||||
| // Context-replay messages: extract the actual new user message | ||||||||
| if ( | ||||||||
| msg.role === 'user' && | ||||||||
| text.startsWith('[Chat messages since your last reply') | ||||||||
| ) { | ||||||||
| const marker = '[Current message - respond to this]' | ||||||||
| const idx = text.indexOf(marker) | ||||||||
| if (idx >= 0) { | ||||||||
| let actual = text.slice(idx + marker.length).trim() | ||||||||
| // Strip "User: " prefix | ||||||||
| actual = actual.replace(/^User:\s*/i, '') | ||||||||
| if (actual) { | ||||||||
| result.push({ | ||||||||
| ...msg, | ||||||||
| content: [{ type: 'text', text: actual }], | ||||||||
| }) | ||||||||
| } | ||||||||
| } | ||||||||
| continue | ||||||||
| } | ||||||||
|
|
||||||||
| result.push(msg) | ||||||||
| } | ||||||||
|
|
||||||||
| return result | ||||||||
| } | ||||||||
|
|
||||||||
| function getCreateAgentValidationError(body: { name?: string }): string | null { | ||||||||
| if (!body.name?.trim()) { | ||||||||
| return 'Name is required' | ||||||||
|
|
@@ -344,6 +408,52 @@ export function createOpenClawRoutes() { | |||||||
| } | ||||||||
| }) | ||||||||
|
|
||||||||
| .get('/agents/:id/history', async (c) => { | ||||||||
| const { id } = c.req.param() | ||||||||
| const limit = Number(c.req.query('limit')) || 10 | ||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Prompt To Fix With AIThis is a comment left during a code review.
Path: packages/browseros-agent/apps/server/src/api/routes/openclaw.ts
Line: 413
Comment:
**`limit=0` silently becomes 10**
`Number('0') || 10` evaluates to `10` because `0` is falsy. A caller explicitly passing `?limit=0` would get 10 sessions back, not 0. Use `Number(...) || 10` only when `NaN` is the expected bad input — otherwise check for `NaN` explicitly.
```suggestion
const limitParam = Number(c.req.query('limit'))
const limit = Number.isNaN(limitParam) || limitParam <= 0 ? 10 : limitParam
```
How can I resolve this? If you propose a fix, please make it concise. |
||||||||
|
|
||||||||
| try { | ||||||||
| const allSessions = await getOpenClawService().listSessions(id) | ||||||||
| const filtered = allSessions | ||||||||
| .filter((s) => s.agentId === id || s.key.includes(`agent:${id}:`)) | ||||||||
| .sort((a, b) => b.updatedAt - a.updatedAt) | ||||||||
| .slice(0, limit) | ||||||||
|
|
||||||||
| const classifySource = (key: string): string => { | ||||||||
| if (key.includes(':cron:')) return 'cron' | ||||||||
| if (key.includes(':hook:')) return 'hook' | ||||||||
| if (key.includes('openai-user:browseros')) return 'user-chat' | ||||||||
| if (key.includes('qa-channel')) return 'channel' | ||||||||
| return 'other' | ||||||||
| } | ||||||||
|
|
||||||||
| const entries = await Promise.all( | ||||||||
| filtered.map(async (s) => { | ||||||||
| const source = classifySource(s.key) | ||||||||
| try { | ||||||||
| const rawMessages = await getOpenClawService().getChatHistory( | ||||||||
| s.key, | ||||||||
| ) | ||||||||
|
|
||||||||
| const messages = filterSystemMessages(rawMessages) | ||||||||
|
|
||||||||
| return { session: { ...s, source }, messages } | ||||||||
| } catch { | ||||||||
| return { session: { ...s, source }, messages: [] } | ||||||||
| } | ||||||||
| }), | ||||||||
| ) | ||||||||
|
|
||||||||
| // Filter out entries with no meaningful messages | ||||||||
| const nonEmpty = entries.filter((e) => e.messages.length > 0) | ||||||||
|
|
||||||||
| return c.json({ entries: nonEmpty }) | ||||||||
| } catch (err) { | ||||||||
| const message = err instanceof Error ? err.message : String(err) | ||||||||
| return c.json({ error: message }, 500) | ||||||||
| } | ||||||||
| }) | ||||||||
|
|
||||||||
| .get('/logs', async (c) => { | ||||||||
| try { | ||||||||
| const logs = await getOpenClawService().getLogs() | ||||||||
|
|
||||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sessions are sorted by
messages[0]?.timestamp ?? 0, buttimestampis an optional field onChatHistoryMessage, so every session without timestamps collapses to the same key and ordering becomes undefined. The session object already carries a reliableupdatedAtfield — prefer that as the sort key.Prompt To Fix With AI