feat(chat): preserve pinned messages across compaction

Add pin and unpin actions for user and assistant text messages, with clear compaction-survival labels, localized tooltips, status-info active styling, and VS Code gating where the server runtime is unavailable.

Persist pinned message IDs, creation timestamps, and roles under the OpenChamber session metadata namespace using fresh-read merge updates so goal, review, and other metadata remain intact.

Introduce a server runtime that reacts to OpenCode's dedicated session.compacted event, fetches pinned messages by ID, extracts and chronologically orders their text parts, and injects them as hidden synthetic context through prompt_async. The restoration prompt tells the agent to use the context silently while work remains and limits idle summaries to one short paragraph.

Track the last handled compaction summary to avoid replay duplication, tolerate individually missing pinned messages, integrate runtime shutdown, document ownership and limitations, and cover metadata round trips plus compaction injection behavior with focused tests.
This commit is contained in:
Bohdan Triapitsyn
2026-07-17 10:30:45 +03:00
parent 53d2dde87a
commit bd68e303d4
20 changed files with 457 additions and 2 deletions
@@ -31,6 +31,12 @@ import { FadeInOnReveal } from './message/FadeInOnReveal';
import { streamPerfCount } from '@/stores/utils/streamDebug';
import { areOptionalRenderRelevantMessagesEqual, areRenderRelevantMessagesEqual, areRelevantTurnGroupingContextsEqual } from './message/renderCompare';
import type { ReviewTransferDirection } from '@/lib/reviewFlow';
import { toast } from 'sonner';
import { useI18n } from '@/lib/i18n';
import { useGlobalSessionsStore } from '@/stores/useGlobalSessionsStore';
import { getContextObligatoryMessages } from '@/lib/contextObligatoryMessages';
import { setContextObligatoryMessage } from '@/sync/session-actions';
import { isVSCodeRuntime } from '@/lib/desktop';
const ToolOutputDialog = lazyWithChunkRecovery(() => import('./message/ToolOutputDialog'));
@@ -150,8 +156,10 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
onUserAnimationConsumed,
reviewTransferDirection = null,
}) => {
const { t } = useI18n();
const { isMobile, isTablet, hasTouchInput } = useDeviceInfo();
const alwaysShowMessageActions = isMobile || isTablet;
const canPinIntoContext = !isVSCodeRuntime();
const { currentTheme } = useThemeSystem();
const messageContainerRef = React.useRef<HTMLDivElement | null>(null);
@@ -402,6 +410,29 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
const timeInfo = message.info.time as { created?: number } | undefined;
return typeof timeInfo?.created === 'number' ? timeInfo.created : null;
}, [message.info.time]);
const isPinnedIntoContext = useGlobalSessionsStore((state) => {
const session = state.activeSessions.find((candidate) => candidate.id === sessionId)
?? state.archivedSessions.find((candidate) => candidate.id === sessionId);
return getContextObligatoryMessages(session).some((entry) => entry.id === message.info.id);
});
const [pinPending, setPinPending] = React.useState(false);
const handleToggleContextPin = React.useCallback(async () => {
if (!sessionId || !messageCreatedAt || pinPending) return;
setPinPending(true);
try {
const directory = useSessionUIStore.getState().getDirectoryForSession(sessionId);
await setContextObligatoryMessage(sessionId, directory, {
id: message.info.id,
createdAt: messageCreatedAt,
role: isUser ? 'user' : 'assistant',
}, !isPinnedIntoContext);
} catch (error) {
console.error('[chat-message] failed to update context pin', error);
toast.error(t('chat.messageBody.actions.contextPinFailed'));
} finally {
setPinPending(false);
}
}, [isPinnedIntoContext, isUser, message.info.id, messageCreatedAt, pinPending, sessionId, t]);
const isMessageCompleted = React.useMemo(() => {
if (isUser) return true;
@@ -1038,6 +1069,9 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
agentMention={agentMention}
onRevert={handleRevert}
onFork={isUser ? handleFork : undefined}
contextPinned={isPinnedIntoContext}
contextPinPending={pinPending}
onToggleContextPin={canPinIntoContext && messageCreatedAt ? handleToggleContextPin : undefined}
errorMessage={assistantErrorText}
errorVariant={assistantErrorVariant}
userActionsMode={useExternalUserActionsRow ? 'external-content' : 'inline'}
@@ -1072,6 +1106,9 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
agentMention={agentMention}
onRevert={handleRevert}
onFork={isUser ? handleFork : undefined}
contextPinned={isPinnedIntoContext}
contextPinPending={pinPending}
onToggleContextPin={canPinIntoContext && messageCreatedAt ? handleToggleContextPin : undefined}
errorMessage={assistantErrorText}
errorVariant={assistantErrorVariant}
userActionsMode="external-actions"
@@ -1104,6 +1141,9 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
messageFinish={messageFinish}
messageCompletedAt={messageCompletedAt ?? undefined}
messageCreatedAt={messageCreatedAt ?? undefined}
contextPinned={isPinnedIntoContext}
contextPinPending={pinPending}
onToggleContextPin={canPinIntoContext && messageCreatedAt ? handleToggleContextPin : undefined}
isMobile={isMobile}
alwaysShowActions={alwaysShowMessageActions}
hasTouchInput={hasTouchInput}
@@ -434,6 +434,9 @@ interface MessageBodyProps {
userActionsMode?: 'inline' | 'external-content' | 'external-actions';
stickyUserHeaderEnabled?: boolean;
reviewTransferDirection?: ReviewTransferDirection | null;
contextPinned?: boolean;
contextPinPending?: boolean;
onToggleContextPin?: () => void;
}
const TOOL_REVEAL_CACHE_MAX = 200;
@@ -454,7 +457,7 @@ const writeRevealedToolIds = (messageId: string, value: Set<string>): void => {
revealedToolIdsByMessage.set(messageId, new Set(value));
};
const UserMessageBody = React.memo(({ messageId, parts, messageCreatedAt, isMobile, alwaysShowActions = isMobile, hasTouchInput, hasTextContent, onCopyMessage, copiedMessage, onShowPopup, agentMention, onRevert, onFork, userActionsMode = 'inline', stickyUserHeaderEnabled = true }: {
const UserMessageBody = React.memo(({ messageId, parts, messageCreatedAt, isMobile, alwaysShowActions = isMobile, hasTouchInput, hasTextContent, onCopyMessage, copiedMessage, onShowPopup, agentMention, onRevert, onFork, contextPinned, contextPinPending, onToggleContextPin, userActionsMode = 'inline', stickyUserHeaderEnabled = true }: {
messageId: string;
parts: Part[];
messageCreatedAt?: number | null;
@@ -468,6 +471,9 @@ const UserMessageBody = React.memo(({ messageId, parts, messageCreatedAt, isMobi
agentMention?: AgentMentionInfo;
onRevert?: () => void;
onFork?: () => void;
contextPinned?: boolean;
contextPinPending?: boolean;
onToggleContextPin?: () => void;
userActionsMode?: 'inline' | 'external-content' | 'external-actions';
stickyUserHeaderEnabled?: boolean;
}) => {
@@ -554,7 +560,7 @@ const UserMessageBody = React.memo(({ messageId, parts, messageCreatedAt, isMobi
const formatted = formatTimestampForDisplay(messageCreatedAt, timeFormatPreference);
return formatted.length > 0 ? formatted : null;
}, [locale, messageCreatedAt, timeFormatPreference]);
const actionsBlock = ((canCopyMessage && hasCopyableText) || onRevert || effectiveOnFork) && showUserActions ? (
const actionsBlock = ((canCopyMessage && hasCopyableText) || onRevert || effectiveOnFork || onToggleContextPin) && showUserActions ? (
<div className={cn(
'group/user-actions',
isMobile
@@ -638,6 +644,29 @@ const UserMessageBody = React.memo(({ messageId, parts, messageCreatedAt, isMobi
<TooltipContent sideOffset={6}>{t('chat.messageBody.actions.fork')}</TooltipContent>
</Tooltip>
)}
{onToggleContextPin && hasCopyableText && (
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className={cn(
'h-6 w-6 bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50',
contextPinned ? 'text-[color:var(--status-info)]' : 'text-muted-foreground',
)}
disabled={contextPinPending}
aria-pressed={contextPinned}
aria-label={t(contextPinned ? 'chat.messageBody.actions.unpinContext' : 'chat.messageBody.actions.pinContext')}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => { event.stopPropagation(); onToggleContextPin(); }}
>
<Icon name={contextPinned ? 'pushpin-2-fill' : 'pushpin-2'} className="h-3 w-3" />
</Button>
</TooltipTrigger>
<TooltipContent sideOffset={6}>{t(contextPinned ? 'chat.messageBody.actions.unpinContext' : 'chat.messageBody.actions.pinContext')}</TooltipContent>
</Tooltip>
)}
{canCopyMessage && hasCopyableText && (
<Tooltip>
<TooltipTrigger asChild>
@@ -1057,6 +1086,9 @@ const AssistantMessageBody = React.memo(({
errorMessage,
errorVariant = 'error',
reviewTransferDirection = null,
contextPinned,
contextPinPending,
onToggleContextPin,
}: Omit<MessageBodyProps, 'isUser'>) => {
const { t, locale } = useI18n();
const chatSurfaceMode = useChatSurfaceMode();
@@ -2003,6 +2035,29 @@ const AssistantMessageBody = React.memo(({
<TooltipContent sideOffset={6}>{t('chat.messageBody.actions.saveAsPlan')}</TooltipContent>
</Tooltip>
) : null}
{onToggleContextPin && hasCopyableText ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className={cn(
'h-8 w-8 bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50',
contextPinned ? 'text-[color:var(--status-info)]' : 'text-muted-foreground',
)}
disabled={contextPinPending}
aria-pressed={contextPinned}
aria-label={t(contextPinned ? 'chat.messageBody.actions.unpinContext' : 'chat.messageBody.actions.pinContext')}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => { event.stopPropagation(); onToggleContextPin(); }}
>
<Icon name={contextPinned ? 'pushpin-2-fill' : 'pushpin-2'} className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent sideOffset={6}>{t(contextPinned ? 'chat.messageBody.actions.unpinContext' : 'chat.messageBody.actions.pinContext')}</TooltipContent>
</Tooltip>
) : null}
{!isMiniChatSurface && !isReviewSessionView ? <Tooltip>
<TooltipTrigger asChild>
<Button
@@ -2176,6 +2231,9 @@ const MessageBody = React.memo(({ isUser, ...props }: MessageBodyProps) => {
agentMention={props.agentMention}
onRevert={props.onRevert}
onFork={props.onFork}
contextPinned={props.contextPinned}
contextPinPending={props.contextPinPending}
onToggleContextPin={props.onToggleContextPin}
userActionsMode={props.userActionsMode}
stickyUserHeaderEnabled={props.stickyUserHeaderEnabled}
/>