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}
/>
@@ -0,0 +1,20 @@
import { describe, expect, test } from 'bun:test';
import { getContextObligatoryMessages, withContextObligatoryMessage } from './contextObligatoryMessages';
describe('context obligatory message metadata', () => {
test('preserves sibling metadata while pinning and unpinning without duplicates', () => {
const message = { id: 'msg_1', createdAt: 10, role: 'user' as const };
const initial = { openchamber: { goal: { id: 'goal_1' } }, external: true };
const pinned = withContextObligatoryMessage(initial, message, true);
const repinned = withContextObligatoryMessage(pinned, message, true);
const session = { metadata: repinned } as never;
expect(getContextObligatoryMessages(session)).toEqual([message]);
expect((repinned.openchamber as Record<string, unknown>).goal).toEqual({ id: 'goal_1' });
expect(withContextObligatoryMessage(repinned, message, false)).toEqual({
external: true,
openchamber: { goal: { id: 'goal_1' }, context_obligatory_messages: [] },
});
});
});
@@ -0,0 +1,48 @@
import type { Session } from '@opencode-ai/sdk/v2';
import { getSessionMetadata, type SessionMetadataRecord } from './sessionReviewMetadata';
export type ContextObligatoryMessage = {
id: string;
createdAt: number;
role: 'user' | 'assistant';
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
Boolean(value && typeof value === 'object' && !Array.isArray(value));
export const getContextObligatoryMessages = (
session: Session | null | undefined,
): ContextObligatoryMessage[] => {
const openchamber = getSessionMetadata(session).openchamber;
if (!isRecord(openchamber) || !Array.isArray(openchamber.context_obligatory_messages)) return [];
return openchamber.context_obligatory_messages.filter((value): value is ContextObligatoryMessage =>
isRecord(value)
&& typeof value.id === 'string'
&& typeof value.createdAt === 'number'
&& Number.isFinite(value.createdAt)
&& (value.role === 'user' || value.role === 'assistant'));
};
export const withContextObligatoryMessage = (
metadata: SessionMetadataRecord,
message: ContextObligatoryMessage,
pinned: boolean,
): SessionMetadataRecord => {
const openchamber = isRecord(metadata.openchamber) ? metadata.openchamber : {};
const current = Array.isArray(openchamber.context_obligatory_messages)
? openchamber.context_obligatory_messages.filter((value): value is ContextObligatoryMessage =>
isRecord(value) && typeof value.id === 'string')
: [];
const withoutMessage = current.filter((value) => value.id !== message.id);
const nextMessages = pinned ? [...withoutMessage, message] : withoutMessage;
return {
...metadata,
openchamber: {
...openchamber,
context_obligatory_messages: nextMessages,
},
};
};
+3
View File
@@ -1886,6 +1886,9 @@ export const dict = {
'chat.messageBody.actions.fork': 'Fork from here',
'chat.messageBody.actions.copyMessageAria': 'Copy message text',
'chat.messageBody.actions.copyMessage': 'Copy message',
'chat.messageBody.actions.pinContext': 'Pin into context (survives compaction)',
'chat.messageBody.actions.unpinContext': 'Unpin from context (will not survive compaction)',
'chat.messageBody.actions.contextPinFailed': 'Could not update the context pin',
'chat.messageBody.actions.openPreviewAria': 'Open preview',
'chat.messageBody.actions.openPreview': 'Open preview',
'chat.messageBody.actions.copyAnswer': 'Copy answer',
+3
View File
@@ -1864,6 +1864,9 @@ export const dict: Record<I18nKey, string> = {
"chat.messageBody.actions.fork": "Bifurcar desde aquí",
"chat.messageBody.actions.copyMessageAria": "Copiar texto del mensaje",
"chat.messageBody.actions.copyMessage": "Copiar mensaje",
"chat.messageBody.actions.pinContext": "Fijar en el contexto (se conserva tras la compactación)",
"chat.messageBody.actions.unpinContext": "Quitar del contexto (no se conservará tras la compactación)",
"chat.messageBody.actions.contextPinFailed": "No se pudo actualizar el mensaje fijado en el contexto",
"chat.messageBody.actions.openPreviewAria": "Abrir vista previa",
"chat.messageBody.actions.openPreview": "Abrir vista previa",
"chat.messageBody.actions.copyAnswer": "Copiar respuesta",
+3
View File
@@ -1679,6 +1679,9 @@ export const dict = {
'chat.messageBody.actions.fork': 'Fourche d\'ici',
'chat.messageBody.actions.copyMessageAria': 'Copier le texte du message',
'chat.messageBody.actions.copyMessage': 'Copier le message',
'chat.messageBody.actions.pinContext': 'Épingler dans le contexte (conservé après compactage)',
'chat.messageBody.actions.unpinContext': 'Désépingler du contexte (non conservé après compactage)',
'chat.messageBody.actions.contextPinFailed': 'Impossible de modifier l’épinglage dans le contexte',
'chat.messageBody.actions.openPreviewAria': 'Ouvrir l\'aperçu',
'chat.messageBody.actions.openPreview': 'Ouvrir l\'aperçu',
'chat.messageBody.actions.copyAnswer': 'Copier la réponse',
+3
View File
@@ -1882,6 +1882,9 @@ export const dict: Record<I18nKey, string> = {
'chat.messageBody.actions.fork': 'ここからフォーク',
'chat.messageBody.actions.copyMessageAria': 'メッセージテキストをコピー',
'chat.messageBody.actions.copyMessage': 'メッセージをコピー',
'chat.messageBody.actions.pinContext': 'コンテキストに固定(圧縮後も保持)',
'chat.messageBody.actions.unpinContext': 'コンテキストから固定解除(圧縮後は保持されません)',
'chat.messageBody.actions.contextPinFailed': 'コンテキストの固定を更新できませんでした',
'chat.messageBody.actions.openPreviewAria': 'プレビューを開く',
'chat.messageBody.actions.openPreview': 'プレビューを開く',
'chat.messageBody.actions.copyAnswer': '回答をコピー',
+3
View File
@@ -1888,6 +1888,9 @@ export const dict: Record<I18nKey, string> = {
'chat.messageBody.actions.fork': '여기서 분기 시작',
'chat.messageBody.actions.copyMessageAria': '메시지 텍스트 복사',
'chat.messageBody.actions.copyMessage': '메시지 복사',
'chat.messageBody.actions.pinContext': '컨텍스트에 고정(압축 후에도 유지)',
'chat.messageBody.actions.unpinContext': '컨텍스트에서 고정 해제(압축 후 유지되지 않음)',
'chat.messageBody.actions.contextPinFailed': '컨텍스트 고정을 업데이트하지 못했습니다',
'chat.messageBody.actions.copyAnswer': '답변 복사',
'chat.messageBody.actions.savingImage': '이미지 저장 중…',
'chat.messageBody.actions.saveAsImage': '이미지로 저장',
+3
View File
@@ -777,6 +777,9 @@ export const dict: Record<I18nKey, string> = {
'chat.messageBody.actions.fork': 'Rozwidl od tego miejsca',
'chat.messageBody.actions.copyMessageAria': 'Kopiuj tekst wiadomości',
'chat.messageBody.actions.copyMessage': 'Kopiuj wiadomość',
'chat.messageBody.actions.pinContext': 'Przypnij do kontekstu (przetrwa kompakcję)',
'chat.messageBody.actions.unpinContext': 'Odepnij od kontekstu (nie przetrwa kompakcji)',
'chat.messageBody.actions.contextPinFailed': 'Nie udało się zaktualizować przypięcia w kontekście',
'chat.messageBody.actions.openPreviewAria': 'Otwórz podgląd',
'chat.messageBody.actions.openPreview': 'Otwórz podgląd',
'chat.messageBody.actions.copyAnswer': 'Kopiuj odpowiedź',
@@ -1864,6 +1864,9 @@ export const dict: Record<I18nKey, string> = {
"chat.messageBody.actions.fork": "Bifurcar daqui",
"chat.messageBody.actions.copyMessageAria": "Copiar texto da mensagem",
"chat.messageBody.actions.copyMessage": "Copiar mensagem",
"chat.messageBody.actions.pinContext": "Fixar no contexto (permanece após a compactação)",
"chat.messageBody.actions.unpinContext": "Desafixar do contexto (não permanece após a compactação)",
"chat.messageBody.actions.contextPinFailed": "Não foi possível atualizar a fixação no contexto",
"chat.messageBody.actions.openPreviewAria": "Abrir visualização",
"chat.messageBody.actions.openPreview": "Abrir visualização",
"chat.messageBody.actions.copyAnswer": "Copiar resposta",
+3
View File
@@ -1864,6 +1864,9 @@ export const dict: Record<I18nKey, string> = {
"chat.messageBody.actions.fork": "Відгалузити звідси",
"chat.messageBody.actions.copyMessageAria": "Копіювати текст повідомлення",
"chat.messageBody.actions.copyMessage": "Копіювати повідомлення",
"chat.messageBody.actions.pinContext": "Закріпити в контексті (збережеться після стиснення)",
"chat.messageBody.actions.unpinContext": "Відкріпити від контексту (не збережеться після стиснення)",
"chat.messageBody.actions.contextPinFailed": "Не вдалося оновити закріплення в контексті",
"chat.messageBody.actions.openPreviewAria": "Відкрити попередній перегляд",
"chat.messageBody.actions.openPreview": "Відкрити попередній перегляд",
"chat.messageBody.actions.copyAnswer": "Скопіювати відповідь",
@@ -1852,6 +1852,9 @@ export const dict: Record<I18nKey, string> = {
'chat.messageBody.actions.fork': '从此处分叉',
'chat.messageBody.actions.copyMessageAria': '复制消息文本',
'chat.messageBody.actions.copyMessage': '复制消息',
'chat.messageBody.actions.pinContext': '固定到上下文(压缩后仍保留)',
'chat.messageBody.actions.unpinContext': '从上下文取消固定(压缩后不再保留)',
'chat.messageBody.actions.contextPinFailed': '无法更新上下文固定状态',
'chat.messageBody.actions.openPreviewAria': '打开预览',
'chat.messageBody.actions.openPreview': '打开预览',
'chat.messageBody.actions.copyAnswer': '复制回答',
@@ -1856,6 +1856,9 @@ export const dict: Record<I18nKey, string> = {
'chat.messageBody.actions.fork': '從此處分支',
'chat.messageBody.actions.copyMessageAria': '複製訊息文字',
'chat.messageBody.actions.copyMessage': '複製訊息',
'chat.messageBody.actions.pinContext': '釘選到內容脈絡(壓縮後仍保留)',
'chat.messageBody.actions.unpinContext': '從內容脈絡取消釘選(壓縮後不再保留)',
'chat.messageBody.actions.contextPinFailed': '無法更新內容脈絡釘選狀態',
'chat.messageBody.actions.openPreviewAria': '開啟預覽',
'chat.messageBody.actions.openPreview': '開啟預覽',
'chat.messageBody.actions.copyAnswer': '複製回答',
+14
View File
@@ -27,6 +27,7 @@ import {
withoutReviewSessionLink,
type SessionMetadataRecord,
} from "@/lib/sessionReviewMetadata"
import { withContextObligatoryMessage, type ContextObligatoryMessage } from "@/lib/contextObligatoryMessages"
const MESSAGE_REFETCH_LIMIT = 100
const SEND_CONFIRMATION_REFETCH_LIMIT = 30
@@ -472,6 +473,19 @@ export async function patchSessionMetadata(
return updated
}
export async function setContextObligatoryMessage(
sessionId: string,
directory: string | null | undefined,
message: ContextObligatoryMessage,
pinned: boolean,
): Promise<Session> {
const updated = await patchSessionMetadata(sessionId, directory, (metadata) =>
withContextObligatoryMessage(metadata, message, pinned))
const sessionDirectory = (updated as Session & { directory?: string | null }).directory ?? directory ?? undefined
mirrorSessionIntoLiveStores(updated, sessionDirectory ?? undefined)
return updated
}
async function cleanupReviewMetadataBeforeDelete(sessionId: string, directory?: string | null): Promise<void> {
let session: Session
try {
+7
View File
@@ -74,6 +74,7 @@ import { createSessionRuntime } from './lib/opencode/session-runtime.js';
import { createOpenCodeWatcherRuntime } from './lib/opencode/watcher.js';
import { createSessionAssistRuntime } from './lib/session-assist/runtime.js';
import { createSessionGoalRuntime } from './lib/session-goal/runtime.js';
import { createContextObligatoryRuntime } from './lib/context-obligatory/runtime.js';
import { createScheduledTasksRuntime } from './lib/scheduled-tasks/runtime.js';
import { createServerStartupRuntime } from './lib/opencode/server-startup-runtime.js';
import { createTunnelWiringRuntime } from './lib/opencode/tunnel-wiring-runtime.js';
@@ -768,6 +769,10 @@ const sessionGoalRuntime = createSessionGoalRuntime({
});
},
});
const contextObligatoryRuntime = createContextObligatoryRuntime({
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
});
const globalMessageStreamHub = createGlobalMessageStreamHub({
buildOpenCodeUrl,
@@ -813,6 +818,7 @@ globalMessageStreamHub.subscribeEvent((event) => {
: '';
sessionAssistRuntime.processPayload(payload, directory);
sessionGoalRuntime.processPayload(payload, directory);
contextObligatoryRuntime.processPayload(payload, directory);
});
const processForwardedEventPayload = (payload, emitSyntheticEvent) => {
@@ -1130,6 +1136,7 @@ const gracefulShutdownRuntime = createGracefulShutdownRuntime({
openCodeWatcherRuntime,
sessionAssistRuntime,
sessionGoalRuntime,
contextObligatoryRuntime,
sessionRuntime,
getHealthCheckInterval: () => healthCheckInterval,
clearHealthCheckInterval: (value) => clearInterval(value),
@@ -0,0 +1,19 @@
# Context Obligatory Messages
Messages explicitly pinned by the user are stored under
`session.metadata.openchamber.context_obligatory_messages` as `{ id, createdAt,
role }`. The UI uses a fresh-read metadata merge when pinning or unpinning.
The server runtime listens for OpenCode's dedicated `session.compacted` event.
It fetches every pinned message by ID, keeps non-empty text parts, sorts them
by the stored creation time, and immediately sends one synthetic user part
through `prompt_async`. OpenCode's session runner serializes this with its own
post-compaction continuation. Missing individual messages are skipped without
discarding the remaining context. Ordinary idle events perform no work and
make no requests.
After a successful send, the runtime merge-writes
`context_obligatory_last_compaction_message_id`. This cursor prevents a
replayed compaction event from reinjecting the same summary. The runtime is
owned by the OpenChamber web backend and therefore is not available in
extension-only VS Code mode.
@@ -0,0 +1,140 @@
const FETCH_TIMEOUT_MS = 15_000;
const MESSAGE_FETCH_LIMIT = 20;
const isRecord = (value) => Boolean(value && typeof value === 'object' && !Array.isArray(value));
const readContextState = (session) => {
const metadata = isRecord(session?.metadata) ? session.metadata : {};
const openchamber = isRecord(metadata.openchamber) ? metadata.openchamber : {};
const messages = Array.isArray(openchamber.context_obligatory_messages)
? openchamber.context_obligatory_messages.filter((item) =>
isRecord(item)
&& typeof item.id === 'string'
&& typeof item.createdAt === 'number'
&& (item.role === 'user' || item.role === 'assistant'))
: [];
return { metadata, openchamber, messages };
};
const buildContextPrompt = (entries) => {
const timeline = entries.map(({ pinned, text }) => {
const timestamp = new Date(pinned.createdAt).toISOString();
return `## ${pinned.role}${timestamp}\n\n${text}`;
}).join('\n\n---\n\n');
return [
'The following messages are from the compacted conversation. The user explicitly marked them as important and required in your context. Pay close attention to them; they may have been sent by either the user or you before compaction.',
'Use them while continuing the pre-compaction work. Do not treat this context restoration as a new standalone task.',
'If any tasks or next steps remain, do not acknowledge, summarize, or mention this restored context in a separate response. Simply continue the work and use it silently as background context. Do not append a recap of it after completing those tasks. Only if no tasks or next steps remain, give the user a very brief summary of the important restored context in no more than one short paragraph, without lists or a detailed recap.',
'',
timeline,
].join('\n');
};
export const createContextObligatoryRuntime = ({
buildOpenCodeUrl,
getOpenCodeAuthHeaders,
}) => {
const inflight = new Set();
let stopped = false;
const openCodeFetch = async (fetchPath, { directory, method = 'GET', body, query } = {}) => {
const params = new URLSearchParams(query || {});
if (directory) params.set('directory', directory);
const search = params.toString();
const response = await fetch(`${buildOpenCodeUrl(fetchPath, '')}${search ? `?${search}` : ''}`, {
method,
headers: {
Accept: 'application/json',
...(body ? { 'Content-Type': 'application/json' } : {}),
...getOpenCodeAuthHeaders(),
},
...(body ? { body: JSON.stringify(body) } : {}),
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!response.ok) throw new Error(`OpenCode ${method} ${fetchPath} failed with ${response.status}`);
return response.json().catch(() => null);
};
const tick = async (sessionId, directory) => {
const session = await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, { directory });
if (session?.parentID) return;
const state = readContextState(session);
if (state.messages.length === 0) return;
const recent = await openCodeFetch(`/session/${encodeURIComponent(sessionId)}/message`, {
directory,
query: { limit: String(MESSAGE_FETCH_LIMIT) },
});
if (!Array.isArray(recent) || recent.length === 0) return;
const summary = recent.toReversed().find((message) =>
message?.info?.role === 'assistant' && message.info.summary === true)?.info;
if (!summary?.id || !summary?.time?.completed) return;
if (state.openchamber.context_obligatory_last_compaction_message_id === summary.id) return;
const fetched = await Promise.allSettled(state.messages.map(async (pinned) => {
const message = await openCodeFetch(
`/session/${encodeURIComponent(sessionId)}/message/${encodeURIComponent(pinned.id)}`,
{ directory },
);
const text = Array.isArray(message?.parts)
? message.parts.filter((part) => part?.type === 'text' && typeof part.text === 'string')
.map((part) => part.text.trim()).filter(Boolean).join('\n\n')
: '';
return { pinned, text };
}));
const entries = fetched
.filter((result) => result.status === 'fulfilled' && result.value.text)
.map((result) => result.value)
.sort((left, right) => left.pinned.createdAt - right.pinned.createdAt);
if (entries.length === 0) return;
const executionInfo = recent.toReversed().find((message) =>
message?.info?.role === 'assistant' && message.info.summary !== true)?.info;
const providerID = typeof executionInfo?.providerID === 'string' ? executionInfo.providerID : '';
const modelID = typeof executionInfo?.modelID === 'string' ? executionInfo.modelID : '';
if (!providerID || !modelID) throw new Error('no pre-compaction assistant provider/model');
const agent = typeof executionInfo.agent === 'string' ? executionInfo.agent : executionInfo.mode;
await openCodeFetch(`/session/${encodeURIComponent(sessionId)}/prompt_async`, {
directory,
method: 'POST',
body: {
model: { providerID, modelID },
...(typeof agent === 'string' && agent ? { agent } : {}),
parts: [{ type: 'text', text: buildContextPrompt(entries), synthetic: true }],
},
});
const fresh = await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, { directory });
const freshState = readContextState(fresh);
await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, {
directory,
method: 'PATCH',
body: {
metadata: {
...freshState.metadata,
openchamber: {
...freshState.openchamber,
context_obligatory_last_compaction_message_id: summary.id,
},
},
},
});
};
const processPayload = (payload, directoryHint = '') => {
if (stopped || payload?.type !== 'session.compacted') return;
const sessionId = payload?.properties?.sessionID;
if (typeof sessionId !== 'string' || inflight.has(sessionId)) return;
const directory = payload?.properties?.directory || directoryHint;
inflight.add(sessionId);
return tick(sessionId, directory)
.catch((error) => console.warn('[context-obligatory] injection failed:', error?.message || error))
.finally(() => inflight.delete(sessionId));
};
const stop = () => {
stopped = true;
};
return { processPayload, stop };
};
@@ -0,0 +1,77 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createContextObligatoryRuntime } from './runtime.js';
const json = (body) => new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
describe('context obligatory runtime', () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it('injects pinned text in chronological order after compaction and records the summary cursor', async () => {
const requests = [];
let sessionReads = 0;
vi.stubGlobal('fetch', vi.fn(async (input, init = {}) => {
const url = new URL(typeof input === 'string' ? input : input.url);
requests.push({ path: url.pathname, method: init.method ?? 'GET', body: init.body });
if (url.pathname === '/session/ses_1' && init.method === 'PATCH') return json({});
if (url.pathname === '/session/ses_1') {
sessionReads += 1;
return json({
id: 'ses_1',
metadata: { openchamber: { context_obligatory_messages: [
{ id: 'msg_2', createdAt: 20, role: 'assistant' },
{ id: 'msg_1', createdAt: 10, role: 'user' },
] } },
});
}
if (url.pathname === '/session/ses_1/message') return json([
{ info: { id: 'msg_agent', role: 'assistant', providerID: 'provider', modelID: 'model', agent: 'build' } },
{ info: { id: 'msg_summary', role: 'assistant', summary: true, time: { completed: 30 } } },
]);
if (url.pathname === '/session/ses_1/message/msg_1') return json({ parts: [{ type: 'text', text: 'First' }] });
if (url.pathname === '/session/ses_1/message/msg_2') return json({ parts: [{ type: 'text', text: 'Second' }] });
if (url.pathname === '/session/ses_1/prompt_async') return json({});
throw new Error(`Unexpected ${url.pathname}`);
}));
const runtime = createContextObligatoryRuntime({
buildOpenCodeUrl: (path) => `http://opencode.test${path}`,
getOpenCodeAuthHeaders: () => ({}),
});
await runtime.processPayload({ type: 'session.compacted', properties: { sessionID: 'ses_1' } });
const prompt = requests.find((request) => request.path.endsWith('/prompt_async'));
const payload = JSON.parse(prompt.body);
expect(payload).toMatchObject({
model: { providerID: 'provider', modelID: 'model' },
agent: 'build',
parts: [{ type: 'text', synthetic: true }],
});
expect(payload.parts[0].text.indexOf('First')).toBeLessThan(payload.parts[0].text.indexOf('Second'));
expect(payload.parts[0].text).toContain('continuing the pre-compaction work');
expect(payload.parts[0].text).toContain('use it silently as background context');
expect(payload.parts[0].text).toContain('Only if no tasks or next steps remain');
expect(payload.parts[0].text).toContain('no more than one short paragraph');
const patch = requests.find((request) => request.method === 'PATCH');
expect(JSON.parse(patch.body).metadata.openchamber.context_obligatory_last_compaction_message_id).toBe('msg_summary');
expect(sessionReads).toBe(2);
runtime.stop();
});
it('ignores ordinary idle events without making requests', async () => {
const fetchImpl = vi.fn();
vi.stubGlobal('fetch', fetchImpl);
const runtime = createContextObligatoryRuntime({
buildOpenCodeUrl: (path) => `http://opencode.test${path}`,
getOpenCodeAuthHeaders: () => ({}),
});
await runtime.processPayload({ type: 'session.status', properties: { sessionID: 'ses_1', status: { type: 'idle' } } });
expect(fetchImpl).not.toHaveBeenCalled();
runtime.stop();
});
});
@@ -10,6 +10,7 @@ export const createGracefulShutdownRuntime = (dependencies) => {
sessionRuntime,
sessionAssistRuntime,
sessionGoalRuntime,
contextObligatoryRuntime,
scheduledTasksRuntime,
getHealthCheckInterval,
clearHealthCheckInterval,
@@ -45,6 +46,7 @@ export const createGracefulShutdownRuntime = (dependencies) => {
sessionRuntime.dispose();
sessionAssistRuntime?.stop?.();
sessionGoalRuntime?.stop?.();
contextObligatoryRuntime?.stop?.();
scheduledTasksRuntime?.stop?.();
const healthCheckInterval = getHealthCheckInterval();