Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 155 additions & 7 deletions apps/desktop/src/app/desktop-controller.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,14 @@ import { useMediaQuery } from '@/hooks/use-media-query'
import { useSkinCommand } from '@/themes/use-skin-command'

import { formatRefValue } from '../components/assistant-ui/directive-text'
import { getCronJobs, getSessionMessages, listAllProfileSessions, type SessionInfo, triggerCronJob } from '../hermes'
import {
getCronJobs,
getSessionMessages,
listAllProfileSessions,
type SessionInfo,
type SessionMessage,
triggerCronJob
} from '../hermes'
import { preserveLocalAssistantErrors, toChatMessages } from '../lib/chat-messages'
import {
isMessagingSource,
Expand Down Expand Up @@ -138,6 +145,12 @@ const SkillsView = lazy(async () => ({ default: (await import('./skills')).Skill
// this cadence while the app is open + visible so new runs surface promptly
// instead of waiting for the next user-triggered refreshSessions().
const CRON_POLL_INTERVAL_MS = 30_000
// Messaging-platform turns are written by the background gateway (WeChat,
// Telegram, Discord, ...), not the desktop websocket that drives local chats.
// Poll the bounded messaging slices while visible so inbound platform traffic
// appears in the desktop without requiring a manual refresh or route change.
const MESSAGING_POLL_INTERVAL_MS = 10_000
const ACTIVE_MESSAGING_SESSION_POLL_INTERVAL_MS = 5_000
// The recents list is local-only: cron rows have their own section, and each
// messaging platform (telegram, discord, …) is fetched separately into its own
// self-managed sidebar section (refreshMessagingSessions). Excluding both here
Expand All @@ -148,14 +161,68 @@ const SIDEBAR_EXCLUDED_SOURCES = ['cron', 'subagent', 'tool', ...MESSAGING_SESSI
// external-platform conversations remain, then split per platform in the UI.
const MESSAGING_EXCLUDED_SOURCES = ['cron', ...LOCAL_SESSION_SOURCE_IDS]

// Cheap signature compare so the poll only swaps the atom (and re-renders the
// sidebar) when the visible cron rows actually changed.
// Cheap signature compare so polls only swap atoms (and re-render the sidebar)
// when visible row metadata actually changed.
function sameCronSignature(a: SessionInfo[], b: SessionInfo[]): boolean {
if (a.length !== b.length) {
return false
}

return a.every((session, i) => session.id === b[i]?.id && session.title === b[i]?.title)
return a.every((session, i) => {
const other = b[i]

return (
other != null &&
session.id === other.id &&
session._lineage_root_id === other._lineage_root_id &&
session.title === other.title &&
session.source === other.source &&
session.profile === other.profile &&
session.preview === other.preview &&
session.message_count === other.message_count &&
session.last_active === other.last_active &&
session.ended_at === other.ended_at
)
})
}

function sessionMatchesStoredId(session: SessionInfo, id: string): boolean {
return session.id === id || session._lineage_root_id === id
}

function hashString(hash: number, value: string): number {
let next = hash

for (let index = 0; index < value.length; index += 1) {
next ^= value.charCodeAt(index)
next = Math.imul(next, 16777619)
}

return next >>> 0
}

function messageContentString(content: unknown): string {
if (typeof content === 'string') {
return content
}

try {
return JSON.stringify(content) ?? ''
} catch {
return String(content)
}
}

function sessionMessagesSignature(messages: SessionMessage[]): string {
let hash = 2166136261

for (const message of messages) {
hash = hashString(hash, message.role)
hash = hashString(hash, String(message.timestamp ?? ''))
hash = hashString(hash, messageContentString(message.content))
}

return `${messages.length}:${hash}`
}

// Rows a session refresh must preserve even if the aggregator omits them:
Expand Down Expand Up @@ -191,6 +258,7 @@ export function DesktopController() {

const busyRef = useRef(false)
const creatingSessionRef = useRef(false)
const messagingTranscriptSignatureRef = useRef(new Map<string, string>())
const refreshSessionsRequestRef = useRef(0)

const gatewayState = useStore($gatewayState)
Expand Down Expand Up @@ -554,9 +622,9 @@ export function DesktopController() {
return
}

const storedProfile = $sessions
.get()
.find(session => session.id === storedSessionId || session._lineage_root_id === storedSessionId)?.profile
const storedProfile = [...$sessions.get(), ...$messagingSessions.get()].find(session =>
sessionMatchesStoredId(session, storedSessionId)
)?.profile

for (let index = 0; index < Math.max(1, attempts); index += 1) {
try {
Expand Down Expand Up @@ -595,6 +663,45 @@ export function DesktopController() {
[activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState]
)

const refreshActiveMessagingTranscript = useCallback(async () => {
const storedSessionId = selectedStoredSessionIdRef.current
const runtimeSessionId = activeSessionIdRef.current

if (!storedSessionId || !runtimeSessionId || busyRef.current) {
return
}

const stored = $messagingSessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))

if (!stored || !isMessagingSource(stored.source)) {
return
}

try {
const latest = await getSessionMessages(storedSessionId, stored.profile)
const signatureKey = `${stored.profile ?? 'default'}:${storedSessionId}`
const signature = sessionMessagesSignature(latest.messages)

if (messagingTranscriptSignatureRef.current.get(signatureKey) === signature) {
return
}

messagingTranscriptSignatureRef.current.set(signatureKey, signature)
const messages = toChatMessages(latest.messages)

updateSessionState(
runtimeSessionId,
state => ({
...state,
messages: preserveLocalAssistantErrors(messages, state.messages)
}),
storedSessionId
)
} catch {
// Non-fatal: the next poll or manual refresh can hydrate the transcript.
}
}, [activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState])

const { handleGatewayEvent } = useMessageStream({
activeSessionIdRef,
hydrateFromStoredSession,
Expand Down Expand Up @@ -794,6 +901,47 @@ export function DesktopController() {
}
}, [gatewayState, refreshCronJobs])

useEffect(() => {
if (gatewayState !== 'open') {
return
}

const tick = () => {
if (document.visibilityState === 'visible') {
void refreshMessagingSessions()
}
}

const intervalId = window.setInterval(tick, MESSAGING_POLL_INTERVAL_MS)
document.addEventListener('visibilitychange', tick)

return () => {
window.clearInterval(intervalId)
document.removeEventListener('visibilitychange', tick)
}
}, [gatewayState, refreshMessagingSessions])

useEffect(() => {
if (gatewayState !== 'open' || !selectedStoredSessionId) {
return
}

const tick = () => {
if (document.visibilityState === 'visible') {
void refreshActiveMessagingTranscript()
}
}

const intervalId = window.setInterval(tick, ACTIVE_MESSAGING_SESSION_POLL_INTERVAL_MS)
document.addEventListener('visibilitychange', tick)
tick()

return () => {
window.clearInterval(intervalId)
document.removeEventListener('visibilitychange', tick)
}
}, [gatewayState, refreshActiveMessagingTranscript, selectedStoredSessionId])

useEffect(() => {
if (gatewayState === 'open' && !activeSessionId && freshDraftReady) {
void refreshCurrentModel()
Expand Down
61 changes: 61 additions & 0 deletions gateway/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,50 @@ def has_any_sessions(self) -> bool:
self._ensure_loaded_locked()
return len(self._entries) > 1

def _compression_tip_for_session_id(self, session_id: Optional[str]) -> Optional[str]:
"""Return the latest compression continuation for ``session_id``.

SessionStore is the durable platform/chat -> session_id mapping. When
an agent compresses context mid-turn, the transcript moves to a child
session, but a restart or failed send can leave this mapping pointing at
the compressed parent. Heal that on read so the next inbound message
resumes the child transcript instead of reloading the parent.
"""
if not session_id or self._db is None:
return session_id
try:
return self._db.get_compression_tip(session_id) or session_id
except Exception:
logger.debug(
"Compression-tip lookup failed for session %s",
session_id,
exc_info=True,
)
return session_id

def _heal_compression_tip_locked(
self,
entry: SessionEntry,
original_session_id: Optional[str],
canonical_session_id: Optional[str],
) -> bool:
"""Rewrite an entry to a known compression continuation if needed."""
if (
not original_session_id
or not canonical_session_id
or entry.session_id != original_session_id
):
return False
if canonical_session_id == entry.session_id:
return False
logger.info(
"SessionStore healed compressed session mapping: %s -> %s",
entry.session_id,
canonical_session_id,
)
entry.session_id = canonical_session_id
return True

def get_or_create_session(
self,
source: SessionSource,
Expand All @@ -904,12 +948,29 @@ def get_or_create_session(
# All _entries / _loaded mutations are protected by self._lock.
db_end_session_id = None
db_create_kwargs = None
existing_session_id = None

if not force_new:
with self._lock:
self._ensure_loaded_locked()
entry = self._entries.get(session_key)
if entry is not None:
existing_session_id = entry.session_id

canonical_existing_session_id = self._compression_tip_for_session_id(
existing_session_id,
) if existing_session_id else None

with self._lock:
self._ensure_loaded_locked()

if session_key in self._entries and not force_new:
entry = self._entries[session_key]
self._heal_compression_tip_locked(
entry,
existing_session_id,
canonical_existing_session_id,
)

# Auto-reset sessions marked as suspended (e.g. after /stop
# broke a stuck loop — #7536). ``suspended`` is the hard
Expand Down
20 changes: 20 additions & 0 deletions tests/gateway/test_restart_resume_pending.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,26 @@ def test_resume_pending_preserves_session_id(self, tmp_path):
# Flag is NOT cleared on read — only on successful turn completion.
assert second.resume_pending is True

def test_resume_pending_follows_compression_tip(self, tmp_path):
"""Interrupted platform mappings must not stay pinned to compressed roots."""
store = _make_store(tmp_path)
source = _make_source(
platform=Platform.WEIXIN,
chat_id="wx-chat",
user_id="wx-user",
)
first = store.get_or_create_session(source)
original_sid = first.session_id
store.mark_resume_pending(first.session_key)

store._db = MagicMock()
store._db.get_compression_tip.return_value = "child-session"

second = store.get_or_create_session(source)
assert second.session_id == "child-session"
assert second.resume_pending is True
store._db.get_compression_tip.assert_called_with(original_sid)

def test_suspended_still_creates_new_session(self, tmp_path):
"""Regression guard — suspended must still force a clean slate."""
store = _make_store(tmp_path)
Expand Down