Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(session): in-place rewind with workspace checkpoint reset (#3469)
nullptr-errord4b9fd0c72e3
diff --git a/docker/Dockerfile.sandbox b/docker/Dockerfile.sandboxindex 6b66c4628..fc6c8db2b 100644--- a/docker/Dockerfile.sandbox+++ b/docker/Dockerfile.sandbox@@ -56,8 +56,9 @@ RUN npm install -g pnpm# image). `file` is not in slim; models reach for it after a script-type error.# curl is not optional: the sandbox connectivity check probes egress with it,# and skills that fetch a URL expect it to be there. The compression tools are-# here because skill bundles and their assets arrive archived. git backs the-# per-turn /workspace checkpoints that session fork rolls back to.+# here because skill bundles and their assets arrive archived. git backs+# per-turn workspace checkpoints (object store at /var/lib/weknora/workspace.git,+# work tree /workspace) that session fork and rewind roll back to.RUN apt-get update && apt-get install -y --no-install-recommends \jq \curl \diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.tsindex e74c199fc..e28c7464b 100644--- a/frontend/src/api/chat/index.ts+++ b/frontend/src/api/chat/index.ts@@ -37,6 +37,13 @@ export async function forkSession(return post(`/api/v1/sessions/${session_id}/fork`, data, { timeout: 180000 });}+export async function rewindSession(+ session_id: string,+ data: { message_id: string },+) {+ return post(`/api/v1/sessions/${session_id}/rewind`, data, { timeout: 180000 });+}+export async function knowledgeChat(data: { session_id: string; query: string; }) {return postChat(`/api/v1/knowledge-chat/${data.session_id}`, { query: data.query, channel: "web" });}diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vueindex fa46e0ca7..ca7fcb7ca 100644--- a/frontend/src/components/Input-field.vue+++ b/frontend/src/components/Input-field.vue@@ -519,6 +519,10 @@ const props = defineProps({type: Boolean,required: false},+ composerLocked: {+ type: Boolean,+ default: false+ },sessionId: {type: String,required: false@@ -1943,6 +1947,9 @@ const createSession = async (delivery: 'inject' | 'after' = 'after',options: SendMessageOptions = {},) => {+ if (props.composerLocked) {+ return;+ }if (!val.trim()) {MessagePlugin.info(t('input.messages.enterContent'));return;@@ -2301,6 +2308,7 @@ const steerShortcutLabel = /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘ Entconst firstQueuedSteer = computed(() => props.queuedSteers.find(item =>item.delivery === 'after' && !item.pending && !item.promoting && !item.failed));const injectCurrentInput = () => {+ if (props.composerLocked) return;if (!props.isReplying || !props.canSteer) return;if (query.value.trim()) void createSession(query.value, 'inject');else if (firstQueuedSteer.value) emit('promote-steer', firstQueuedSteer.value.steer_id);@@ -2350,6 +2358,7 @@ const onKeydown = (val: string, event: { e: KeyboardEvent }) => {const delivery = chatSubmitShortcut(event.e, props.isReplying && props.canSteer);if (delivery) {event.e.preventDefault();+ if (props.composerLocked) return;if (delivery === 'inject' && props.isReplying && props.canSteer) injectCurrentInput();else void createSession(val, delivery);}@@ -2892,7 +2901,7 @@ defineExpose({</t-tooltip><t-tooltip v-else :content="`${isReplying && canSteer ? $t('input.steerAfter') : $t('input.send')} · Enter`"><button type="button" @click="createSession(query)" class="control-btn send-btn" data-guide="chat-send"- :disabled="!query.trim()" :class="{ 'disabled': !query.trim() }"+ :disabled="!query.trim() || composerLocked" :class="{ 'disabled': !query.trim() || composerLocked }":aria-label="isReplying && canSteer ? $t('input.steerAfter') : $t('input.send')"><t-icon name="arrow-up" /></button>diff --git a/frontend/src/components/chat/SandboxSidePanel.test.mjs b/frontend/src/components/chat/SandboxSidePanel.test.mjsindex 4a307de50..6f15d5b20 100644--- a/frontend/src/components/chat/SandboxSidePanel.test.mjs+++ b/frontend/src/components/chat/SandboxSidePanel.test.mjs@@ -29,3 +29,10 @@ test('desktop tab is omitted unless the selected agent sandbox has desktop_enablassert.match(panel, /if \(desktopTabVisible\.value\)/)assert.match(panel, /desktopMounted && desktopTabVisible/)})++test('panel slide-in is clipped to the viewport so it cannot create a document scrollbar', () => {+ assert.match(panel, /chat-sandbox-panel-clip/)+ assert.match(panel, /sandbox-panel-enter-from \.chat-sandbox-panel/)+ assert.match(panel, /translateX\(100%\)/)+ assert.match(panel, /:duration/)+})diff --git a/frontend/src/components/chat/SandboxSidePanel.vue b/frontend/src/components/chat/SandboxSidePanel.vueindex 692c2076a..ca217c5e5 100644--- a/frontend/src/components/chat/SandboxSidePanel.vue+++ b/frontend/src/components/chat/SandboxSidePanel.vue@@ -1,13 +1,13 @@<template>- <Transition name="sandbox-panel">- <aside- v-if="panel?.visible.value"- class="chat-sandbox-panel"- :class="{ 'is-shifted': shifted, 'is-resizing': resizing }"- :style="{ width: `${panel?.width.value ?? 420}px` }"- role="complementary"- :aria-label="t('chat.sandbox.panelTitle')"- >+ <Transition name="sandbox-panel" :duration="{ enter: 240, leave: 300 }">+ <div v-if="panel?.visible.value" class="chat-sandbox-panel-clip">+ <aside+ class="chat-sandbox-panel"+ :class="{ 'is-shifted': shifted, 'is-resizing': resizing }"+ :style="{ width: `${panel?.width.value ?? 420}px` }"+ role="complementary"+ :aria-label="t('chat.sandbox.panelTitle')"+ ><!-- 左缘拖拽把手:按住向左/右拖动调整面板宽度。 --><PanelResizeHandle edge="left" :label="t('knowledgeStages.resizeDrawer')":value="panel.width.value" :min="SANDBOX_PANEL_MIN_WIDTH" :max="SANDBOX_PANEL_MAX_WIDTH"@@ -89,6 +89,7 @@</div></div></aside>+ </div></Transition></template>@@ -238,14 +239,22 @@ function resizePanel(delta: number) {</script><style scoped lang="less">-.chat-sandbox-panel {+.chat-sandbox-panel-clip {position: fixed;+ inset: 0;+ z-index: 1201;+ overflow: hidden;+ pointer-events: none;+}++.chat-sandbox-panel {+ pointer-events: auto;+ position: absolute;top: 0;right: 0;bottom: 0;width: min(420px, 100vw);max-width: 100vw;- z-index: 1201;display: flex;flex-direction: column;background: var(--td-bg-color-container);@@ -390,20 +399,20 @@ function resizePanel(delta: number) {}}-.sandbox-panel-enter-active {+.sandbox-panel-enter-active .chat-sandbox-panel {transition:transform 0.24s cubic-bezier(0.22, 0.61, 0.36, 1),opacity 0.24s cubic-bezier(0.22, 0.61, 0.36, 1);}-.sandbox-panel-leave-active {+.sandbox-panel-leave-active .chat-sandbox-panel {transition:transform 0.3s cubic-bezier(0.22, 0.61, 0.36, 1),opacity 0.3s cubic-bezier(0.22, 0.61, 0.36, 1);}-.sandbox-panel-enter-from,-.sandbox-panel-leave-to {+.sandbox-panel-enter-from .chat-sandbox-panel,+.sandbox-panel-leave-to .chat-sandbox-panel {transform: translateX(100%);opacity: 0.6;}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 8cc98768d..396241eaf 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3713,6 +3713,21 @@ export default {referenceChunkCount: '{count} chunk(s)',fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.',truncatedHint: 'This answer was cut off at the per-response output limit. Above is what the model produced before the cut.',+ rewind: {+ tooltip: 'Rewind to here',+ confirmBody: 'Later messages will be deleted. Rewinding from a question also removes that question and puts it back in the input. The workspace rolls back when a checkpoint is available. This cannot be undone.',+ confirmButton: 'Rewind',+ cancelButton: 'Cancel',+ success: 'Rewound',+ busy: 'Wait until this turn finishes before rewinding',+ noCheckpoint: 'Cannot rewind: this session has a live workspace but no reachable checkpoint',+ sandboxReplaced: 'Cannot rewind: the sandbox was replaced, so the old checkpoint is unreachable',+ reloadFailed: 'Conversation was rewound, but history could not be reloaded. Refresh if older messages are missing',+ failed: 'Rewind failed. Please try again',+ skipped: 'Conversation rewound; workspace was left unchanged',+ skipNoSandbox: 'Conversation rewound; workspace was left unchanged (no sandbox is bound)',+ skipNoCheckpoint: 'Conversation rewound; workspace was left unchanged (no checkpoint to restore)',+ },requestInfoTitle: 'Request info',requestInfoRequestId: 'Request ID',requestInfoMessageId: 'Message ID',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 138557e10..f1de7197d 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -3713,6 +3713,21 @@ export default {referenceChunkCount: '{count}件のチャンク',fallbackHint: 'ナレッジベースから関連する内容が見つかりませんでした。上記はモデルの直接回答です。',truncatedHint: 'モデルの1回あたりの出力上限で回答が途中で打ち切られました。上記は打ち切り前に生成された内容です。',+ rewind: {+ tooltip: 'ここに巻き戻す',+ confirmBody: 'これより後の会話を削除します。質問から巻き戻すとその質問自体も消え、入力欄に戻します。チェックポイントがあればワークスペースも戻します。この操作は元に戻せません。',+ confirmButton: '巻き戻す',+ cancelButton: 'キャンセル',+ success: '巻き戻しました',+ busy: 'このターンの回答が終わるまで待ってから巻き戻してください',+ noCheckpoint: '巻き戻せません。ライブのワークスペースはありますが、到達できるチェックポイントがありません',+ sandboxReplaced: '巻き戻せません。サンドボックスが置き換わったため、古いチェックポイントに到達できません',+ reloadFailed: '会話は巻き戻しましたが、履歴を再読み込みできませんでした。古いメッセージが欠けている場合は更新してください',+ failed: '巻き戻しに失敗しました。もう一度お試しください',+ skipped: '会話は巻き戻しましたが、ワークスペースは変更していません',+ skipNoSandbox: '会話は巻き戻しましたが、ワークスペースは変更していません(サンドボックスがありません)',+ skipNoCheckpoint: '会話は巻き戻しましたが、ワークスペースは変更していません(戻せるチェックポイントがありません)',+ },requestInfoTitle: 'リクエスト情報',requestInfoRequestId: 'Request ID',requestInfoMessageId: 'メッセージID',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex ccbd54bca..11c6a4b31 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -3828,6 +3828,21 @@ export default {referenceChunkCount: '{count}개 청크',fallbackHint: '지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.',truncatedHint: '모델의 응답당 출력 한도에서 답변이 잘렸습니다. 위 내용은 잘리기 전까지 생성된 부분입니다.',+ rewind: {+ tooltip: '여기로 되돌리기',+ confirmBody: '이 메시지 이후의 대화를 삭제합니다. 질문에서 되돌리면 해당 질문도 지워지고 입력창에 다시 채워집니다. 체크포인트가 있으면 작업 영역도 되돌립니다. 이 작업은 취소할 수 없습니다.',+ confirmButton: '되돌리기',+ cancelButton: '취소',+ success: '되돌렸습니다',+ busy: '이번 답변이 끝난 뒤에 되돌리세요',+ noCheckpoint: '되돌릴 수 없습니다. 라이브 작업 영역은 있지만 도달 가능한 체크포인트가 없습니다',+ sandboxReplaced: '되돌릴 수 없습니다. 샌드박스가 교체되어 이전 체크포인트에 도달할 수 없습니다',+ reloadFailed: '대화는 되돌렸지만 기록을 다시 불러오지 못했습니다. 이전 메시지가 없으면 새로고침하세요',+ failed: '되돌리기에 실패했습니다. 다시 시도하세요',+ skipped: '대화는 되돌렸지만 작업 영역은 변경하지 않았습니다',+ skipNoSandbox: '대화는 되돌렸지만 작업 영역은 변경하지 않았습니다(샌드박스가 없음)',+ skipNoCheckpoint: '대화는 되돌렸지만 작업 영역은 변경하지 않았습니다(되돌릴 체크포인트가 없음)',+ },requestInfoTitle: 'Request info',requestInfoRequestId: 'Request ID',requestInfoMessageId: 'Message ID',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 29b1f9f2f..85017f8f3 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -3828,6 +3828,21 @@ export default {referenceChunkCount: '{count} фрагмент(ов)',fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.',truncatedHint: 'Ответ обрезан на лимите вывода модели за один ответ. Выше — то, что было создано до обрыва.',+ rewind: {+ tooltip: 'Откатить сюда',+ confirmBody: 'Сообщения после этой точки будут удалены. Откат от вопроса также убирает сам вопрос и возвращает его во ввод. Рабочая область откатится, если есть контрольная точка. Отменить действие нельзя.',+ confirmButton: 'Откатить',+ cancelButton: 'Отмена',+ success: 'Сессия откачена',+ busy: 'Дождитесь окончания текущего ответа, прежде чем откатывать',+ noCheckpoint: 'Нельзя откатить: есть живая рабочая область, но нет достижимой контрольной точки',+ sandboxReplaced: 'Нельзя откатить: песочница заменена, старая контрольная точка недоступна',+ reloadFailed: 'Диалог откачен, но историю не удалось перезагрузить. Обновите страницу, если пропали более ранние сообщения',+ failed: 'Не удалось откатить. Попробуйте ещё раз',+ skipped: 'Диалог откачен, рабочая область не изменена',+ skipNoSandbox: 'Диалог откачен, рабочая область не изменена (нет привязанной песочницы)',+ skipNoCheckpoint: 'Диалог откачен, рабочая область не изменена (нет контрольной точки для отката)',+ },requestInfoTitle: 'Request info',requestInfoRequestId: 'Request ID',requestInfoMessageId: 'Message ID',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 8ba874f86..e4727925d 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -3830,6 +3830,21 @@ export default {referenceChunkCount: '{count}个片段',fallbackHint: '未从知识库中检索到相关内容,以上为模型直接回答',truncatedHint: '回答在模型单次输出上限处被截断,以上为截断前已生成的内容',+ rewind: {+ tooltip: '回滚到这里',+ confirmBody: '将删除此条之后的对话。从用户消息回滚时会删掉该问题本身,并填回输入框。若有可用检查点,工作区会一并回退。此操作不可撤销。',+ confirmButton: '回滚',+ cancelButton: '取消',+ success: '已回滚',+ busy: '请等本轮回答结束后再回滚',+ noCheckpoint: '无法回滚:当前有沙箱,但没有可回退的检查点',+ sandboxReplaced: '无法回滚:沙箱已更换,无法回退到旧检查点',+ reloadFailed: '对话已回滚,但未能重新加载历史。若较早消息缺失,请刷新页面',+ failed: '回滚失败,请重试',+ skipped: '对话已回滚,工作区未改动',+ skipNoSandbox: '对话已回滚,工作区未改动(当前没有沙箱)',+ skipNoCheckpoint: '对话已回滚,工作区未改动(没有可回退的检查点)',+ },requestInfoTitle: '请求信息',requestInfoRequestId: 'Request ID',requestInfoMessageId: '消息 ID',diff --git a/frontend/src/utils/chatMarkdownRenderer.test.ts b/frontend/src/utils/chatMarkdownRenderer.test.tsindex d860b5573..b7af3ff3f 100644--- a/frontend/src/utils/chatMarkdownRenderer.test.ts+++ b/frontend/src/utils/chatMarkdownRenderer.test.ts@@ -84,6 +84,23 @@ test('renderChatMarkdown safely renders an image with fullwidth parentheses', ()assert.doesNotMatch(html, /(|)/)})+test('renderChatMarkdown skips an image with an empty destination', () => {+ const renderer = createChatMarkdownRenderer({+ imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,+ invalidImageHtml: () => '<p>invalid</p>',+ isValidImageUrl: (href) => Boolean(href),+ })+ const html = renderChatMarkdown('![根目录示例文件]()', {+ renderer,+ escapeMarkdown: (text) => text,+ sanitizeHtml: (value) => value,+ streaming: false,+ })++ assert.doesNotMatch(html, /<img/)+ assert.doesNotMatch(html, /invalid/)+})+test('renderChatMarkdown hides an unfinished fullwidth-parenthesis image while streaming', () => {const renderer = createChatMarkdownRenderer()const html = renderChatMarkdown('before  {renderer.image = ({ href, title, text }: Tokens.Image) => {const imageHref = href || ''+ if (!imageHref.trim()) return ''if (options.isValidImageUrl && !options.isValidImageUrl(imageHref)) {return options.invalidImageHtml?.(imageHref) ?? ''}diff --git a/frontend/src/utils/sandboxArtifactRefs.test.ts b/frontend/src/utils/sandboxArtifactRefs.test.tsindex 6d7c923a2..5f6aaddfe 100644--- a/frontend/src/utils/sandboxArtifactRefs.test.ts+++ b/frontend/src/utils/sandboxArtifactRefs.test.ts@@ -153,6 +153,16 @@ test('after the turn ends an unresolved reference says so instead of hanging', (assert.ok(!html?.includes('role="button"'))})+test('an empty image destination is skipped instead of rendering a broken img', () => {+ const html = renderArtifactReference({+ href: '',+ alt: '根目录示例文件',+ artifacts: [],+ labels,+ })+ assert.equal(html, '')+})+test('file names with spaces and parentheses resolve end to end', () => {const raw = ' 成交量_838ccc.html)'const normalized = normalizeSandboxArtifactRefs(raw)diff --git a/frontend/src/utils/sandboxArtifactRefs.ts b/frontend/src/utils/sandboxArtifactRefs.tsindex d75ac376a..4ec95a861 100644--- a/frontend/src/utils/sandboxArtifactRefs.ts+++ b/frontend/src/utils/sandboxArtifactRefs.ts@@ -305,6 +305,7 @@ function renderImage(** 返回 null 表示这不是沙箱产物引用,调用方应回落到默认渲染(普通图片、* `resource://` 受保护图片、外链等一律不受影响)。+ * 返回空字符串表示目标为空,调用方不应再画裂图。*/export function renderArtifactReference(args: {href: string;@@ -315,10 +316,12 @@ export function renderArtifactReference(args: {/** 本轮回答还在生成中。产物要到本轮结束才会收集,此时解析不到是正常的。 */streaming?: boolean;}): string | null {- const ref = parseArtifactRef(args.href);+ const href = (args.href || '').trim();+ if (!href) return '';+ const ref = parseArtifactRef(href);if (!ref) return null;- const artifact = resolveArtifactRef(args.href, args.artifacts);+ const artifact = resolveArtifactRef(href, args.artifacts);if (!artifact) {// 句柄对不上本消息的产物,说明这是别的受保护文件(知识库检索图、// 附件图……)。交回默认渲染,由 hydrateProtectedFileImages 带鉴权拉取。diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex fcdeb7f37..1e2477191 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -389,6 +389,22 @@<t-icon name="git-branch" /></t-button></t-tooltip>+ <t-popconfirm+ v-if="canRewind"+ :content="t('chat.rewind.confirmBody')"+ :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger' }"+ :cancel-btn="{ content: t('chat.rewind.cancelButton') }"+ theme="warning"+ placement="top"+ overlay-class-name="chat-rewind-popconfirm"+ @confirm="emitRewind"+ >+ <t-tooltip :content="rewindTooltip">+ <t-button size="small" variant="outline" shape="round" @click.stop>+ <t-icon name="rollback" />+ </t-button>+ </t-tooltip>+ </t-popconfirm><t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)":title="$t('agent.copy')"><t-icon name="copy" />@@ -975,19 +991,27 @@ const props = defineProps<{ragMode?: boolean;followUpLoading?: boolean;canFork?: boolean;+ canRewind?: boolean;}>();const emit = defineEmits<{(event: 'render-complete-change', ready: boolean): void;(event: 'fork', messageId: string): void;+ (event: 'rewind', messageId: string): void;}>();const canFork = computed(() => props.canFork === true && !props.embeddedMode)+const canRewind = computed(() => props.canRewind === true && !props.embeddedMode)const forkTooltip = '从这条回答继续分叉'+const rewindTooltip = computed(() => t('chat.rewind.tooltip'))const emitFork = () => {const messageId = persistedAssistantId(props.session) || String(props.session?.id || '')if (messageId) emit('fork', messageId)}+const emitRewind = () => {+ const messageId = persistedAssistantId(props.session) || String(props.session?.id || '')+ if (messageId) emit('rewind', messageId)+}const embedAuthProps = computed(() => ({embeddedMode: props.embeddedMode,diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vueindex b8c392bca..8718fbedd 100644--- a/frontend/src/views/chat/components/botmsg.vue+++ b/frontend/src/views/chat/components/botmsg.vue@@ -20,7 +20,9 @@:user-query="userQuery" :rag-mode="true" :follow-up-loading="followUpLoading":embedded-mode="embeddedMode":can-fork="canFork"+ :can-rewind="canRewind"@fork="emit('fork', $event)"+ @rewind="emit('rewind', $event)"@render-complete-change="emit('render-complete-change', $event)" /></div><template v-else>@@ -35,7 +37,9 @@v-if="session.isAgentMode" :follow-up-loading="followUpLoading":embedded-mode="embeddedMode":can-fork="canFork"+ :can-rewind="canRewind"@fork="emit('fork', $event)"+ @rewind="emit('rewind', $event)"@render-complete-change="emit('render-complete-change', $event)" /></template><deepThink :deepSession="session" v-if="session.showThink && !session.isAgentMode"></deepThink>@@ -55,6 +59,22 @@<t-icon name="git-branch" /></t-button></t-tooltip>+ <t-popconfirm+ v-if="canRewind"+ :content="t('chat.rewind.confirmBody')"+ :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger' }"+ :cancel-btn="{ content: t('chat.rewind.cancelButton') }"+ theme="warning"+ placement="top"+ overlay-class-name="chat-rewind-popconfirm"+ @confirm="emitRewind"+ >+ <t-tooltip :content="rewindTooltip">+ <t-button size="small" variant="outline" shape="round" @click.stop>+ <t-icon name="rollback" />+ </t-button>+ </t-tooltip>+ </t-popconfirm><t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer":title="$t('agent.copy')"><t-icon name="copy" />@@ -178,7 +198,7 @@ const mentionTagIcon = (item) => {return 'file';};-const emit = defineEmits(['scroll-bottom', 'render-complete-change', 'fork'])+const emit = defineEmits(['scroll-bottom', 'render-complete-change', 'fork', 'rewind'])const { t } = useI18n()const uiStore = useUIStore();let parentMd = ref()@@ -223,15 +243,25 @@ const props = defineProps({canFork: {type: Boolean,default: false+ },+ canRewind: {+ type: Boolean,+ default: false}});const canFork = computed(() => props.canFork === true && !props.embeddedMode)+const canRewind = computed(() => props.canRewind === true && !props.embeddedMode)const forkTooltip = '从这条回答继续分叉'+const rewindTooltip = computed(() => t('chat.rewind.tooltip'))const emitFork = () => {const messageId = persistedAssistantId(props.session) || props.session?.idif (messageId) emit('fork', messageId)}+const emitRewind = () => {+ const messageId = persistedAssistantId(props.session) || props.session?.id+ if (messageId) emit('rewind', messageId)+}const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));diff --git a/frontend/src/views/chat/components/usermsg.vue b/frontend/src/views/chat/components/usermsg.vueindex b447e0edf..20bd70666 100644--- a/frontend/src/views/chat/components/usermsg.vue+++ b/frontend/src/views/chat/components/usermsg.vue@@ -43,11 +43,11 @@<div class="user_msg">{{ content }}</div>- <div v-if="timestamp || content || canFork" class="user_msg_meta">+ <div v-if="timestamp || content || canFork || canRewind" class="user_msg_meta"><time v-if="timestamp" class="user_msg_time" :datetime="timestamp.datetime" :title="fullTimestamp">{{ timestamp.time }}</time>- <div v-if="content || canFork" class="user_msg_actions">+ <div v-if="content || canFork || canRewind" class="user_msg_actions"><t-tooltip v-if="content" :content="t('agent.copy')"><button type="button" class="user_msg_action" :aria-label="t('agent.copy')" @click="handleCopy"><t-icon name="copy" />@@ -58,6 +58,22 @@<t-icon name="git-branch" /></button></t-tooltip>+ <t-popconfirm+ v-if="canRewind"+ :content="t('chat.rewind.confirmBody')"+ :confirm-btn="{ content: t('chat.rewind.confirmButton'), theme: 'danger' }"+ :cancel-btn="{ content: t('chat.rewind.cancelButton') }"+ theme="warning"+ placement="top"+ overlay-class-name="chat-rewind-popconfirm"+ @confirm="emit('rewind', messageId)"+ >+ <t-tooltip :content="rewindTooltip">+ <button type="button" class="user_msg_action" :aria-label="rewindTooltip" @click.stop>+ <t-icon name="rollback" />+ </button>+ </t-tooltip>+ </t-popconfirm></div></div><div v-if="steerFailed" class="steer-failure" role="status">@@ -78,7 +94,7 @@ import { isPreviewableAttachment, resolveAttachmentFileType } from '@/utils/attaimport { SKILL_ICON } from '@/types/mention';import { copyWithToast } from '@/utils/clipboard';import { formatMessageTimestamp, getConversationTimestampModel } from '@/utils/messageTimestamp';-const emit = defineEmits(['retry-steer', 'remove-steer', 'fork']);+const emit = defineEmits(['retry-steer', 'remove-steer', 'fork', 'rewind']);const { t } = useI18n();@@ -139,14 +155,20 @@ const props = defineProps({canFork: {type: Boolean,default: false+ },+ canRewind: {+ type: Boolean,+ default: false}});const canFork = computed(() => props.canFork === true && !props.embeddedMode);+const canRewind = computed(() => props.canRewind === true && !props.embeddedMode);const forkTooltip = '从这里分叉出新会话';const timestamp = computed(() => getConversationTimestampModel(props.createdAt));const fullTimestamp = computed(() => formatMessageTimestamp(props.createdAt));const handleCopy = () => copyWithToast(props.content, 'common.copySuccess', 'common.copyFailed');+const rewindTooltip = computed(() => t('chat.rewind.tooltip'));const attachmentPreviewDrawer = useChatAttachmentPreviewDrawer();diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vueindex b1fb0bf7b..ae961679f 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -105,17 +105,20 @@:value="session.created_at" /><div v-if="session.role == 'user'" class="message-row"- :data-message-id="session.id || undefined">+ :data-message-id="session.id || undefined"+ :class="{ 'is-minimap-target': session.id && session.id === minimapTargetId }"><usermsg :content="session.content" :mentioned_items="session.mentioned_items":images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode":session-id="session_id":message-id="session.id":created-at="session.created_at":can-fork="!embeddedMode && forkAffordanceOf(session.id).canFork"+ :can-rewind="canRewindMessage(session.id)":steer-failed="Boolean(session._steerFailed)"@retry-steer="handleRetrySteer(session.steer_id)"@remove-steer="handleRemoveSteer(session.steer_id)"- @fork="handleFork">+ @fork="handleFork"+ @rewind="handleRewind"></usermsg></div><div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)"@@ -126,7 +129,9 @@:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode":follow-up-loading="Boolean(session.suggestionLoading && !session.suggestionSet?.questions?.length)":can-fork="!embeddedMode && forkAffordanceOf(session.id).canFork"+ :can-rewind="canRewindMessage(session.id)"@fork="handleFork"+ @rewind="handleRewind"@render-complete-change="(ready) => handleAnswerRenderComplete(session, ready)"></botmsg><FollowUpSuggestions v-if="session.answerFullyRendered && !session.steerForked && !session.suggestionsDismissed"@@ -159,7 +164,7 @@@retry-steer="handleRetrySteer"@stop-generation="handleStopGeneration"@stop-confirmed="handleStopConfirmed"- @stop-failed="handleStopFailed" :isReplying="isReplying" :sessionId="session_id"+ @stop-failed="handleStopFailed" :isReplying="isReplying" :composer-locked="composerLocked" :sessionId="session_id":assistantMessageId="currentAssistantMessageId" :embeddedMode="embeddedMode":queuedSteers="steerQueue.filter(item => item.delivery === 'after')" :canSteer="isAgentStreamSession()"></InputField></div>@@ -193,8 +198,10 @@ import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vuimport InputField from '../../components/Input-field.vue';import botmsg from './components/botmsg.vue';import usermsg from './components/usermsg.vue';-import { getMessageList, getSession, forkSession } from "@/api/chat/index";+import { getMessageList, getSession, forkSession, rewindSession } from "@/api/chat/index";import { resolveForkAffordance } from './forkPoint';+import { rewindSkipMessage } from './rewindNotice';+import { rewindPrefillText, rewindBlockedByOutgoingWork, canReplaceRewindTranscript, shouldApplyRewindLocally, rewindHistoryHasMore, keepMessagesThroughRewindPoint, rewindableMessageIds, rewindHttpConflictCode, rewindConflictI18nKey } from './rewindView';import { getSuggestedQuestions } from "@/api/agent/index";import { questionOriginFromSuggestion } from '@/utils/questionOrigin';import { deleteTemporaryAttachment, uploadTemporaryAttachment } from '@/api/chat/temporary-attachments';@@ -325,8 +332,24 @@ function forkAffordanceOf(messageId) {return resolveForkAffordance(messagesList, messageId)}+// One pass over the transcript per render instead of two per rendered row:+// the template asks this for every message and re-asks on every streamed token.+const rewindableIds = computed(() => rewindableMessageIds(messagesList, {+ embeddedMode: props.embeddedMode,+ outgoingWork: outgoingWorkBlocksRewind.value,+}))++function canRewindMessage(messageId) {+ return Boolean(messageId) && rewindableIds.value.has(String(messageId))+}+const FORK_PREFILL_KEY = 'weknora:fork-prefill'let forkInFlight = false+const rewindInFlight = ref(false)+const rewindLockSessionId = ref('')+const composerLocked = computed(() =>+ rewindInFlight.value && String(session_id.value || '') === rewindLockSessionId.value+)function stashForkLanding(sessionId, text) {const payload = JSON.stringify({ sessionId, text })@@ -372,7 +395,7 @@ function applyForkLanding() {async function handleFork(messageId) {if (props.embeddedMode) return- if (forkInFlight) return+ if (forkInFlight || composerLocked.value) returnif (!messageId || !session_id.value) returnconst source = messagesList.find((m) => m.id === messageId)if (!source) return@@ -415,6 +438,102 @@ async function handleFork(messageId) {}}+async function handleRewind(messageId) {+ if (props.embeddedMode) return+ if (forkInFlight || composerLocked.value) return+ if (rewindBlockedByOutgoingWork({+ isReplying: isReplying.value,+ isStreaming: isStreaming.value,+ isRecovering: isImRecovering.value,+ })) return+ if (!messageId || !session_id.value) return+ const source = messagesList.find((m) => m.id === messageId || persistedAssistantId(m) === messageId)+ if (!source) return+ const sourceSessionId = session_id.value+ const sourceRole = source.role+ const sourceContent = source.content++ rewindInFlight.value = true+ rewindLockSessionId.value = sourceSessionId+ try {+ const res = await rewindSession(sourceSessionId, { message_id: messageId })+ const data = res?.data+ if (!data) return+ if (!shouldApplyRewindLocally(String(session_id.value || ''), sourceSessionId)) return++ let batch+ let reloadFailed = false+ try {+ const history = await fetchMessageList({+ session_id: sourceSessionId,+ created_at: '',+ limit: limit.value,+ })+ batch = history?.data+ if (!Array.isArray(batch)) {+ throw new Error('rewind history reload returned no list')+ }+ } catch {+ reloadFailed = true+ }+ if (!shouldApplyRewindLocally(String(session_id.value || ''), sourceSessionId)) return++ steerQueue.value = []+ historyLoading.value = false+ if (reloadFailed) {+ const kept = keepMessagesThroughRewindPoint(+ [...messagesList],+ messageId,+ sourceRole,+ (m) => m.id === messageId || persistedAssistantId(m) === messageId,+ )+ messagesList.splice(0, messagesList.length, ...kept)+ // created_at still points at the oldest message we actually hold.+ // Clearing it here would send the next scroll-up back to the newest+ // page, which this prefix already contains, instead of older ones.+ MessagePlugin.warning(t('chat.rewind.reloadFailed'))+ } else {+ if (!canReplaceRewindTranscript(String(session_id.value || ''), sourceSessionId, undefined)) return+ messagesList.splice(0)+ created_at.value = ''+ if (batch.length) {+ created_at.value = batch[0].created_at+ hasMoreHistory.value = rewindHistoryHasMore(batch.length, limit.value)+ await handleMsgList(batch, false)+ } else {+ hasMoreHistory.value = false+ }+ }++ const prefill = rewindPrefillText(sourceRole, sourceContent)+ if (prefill) {+ inputFieldRef.value?.prefill(prefill)+ }++ if (reloadFailed) {+ return+ }+ if (data.workspace_reset) {+ MessagePlugin.success(t('chat.rewind.success'))+ return+ }+ const skip = rewindSkipMessage(String(data.reason || ''), t)+ if (skip) {+ MessagePlugin.info(skip)+ }+ } catch (err) {+ const conflictCode = rewindHttpConflictCode(err)+ if (conflictCode || err?.status === 409 || err?.$httpStatus === 409) {+ MessagePlugin.warning(t(rewindConflictI18nKey(conflictCode)))+ return+ }+ MessagePlugin.error(t('chat.rewind.failed'))+ } finally {+ rewindInFlight.value = false+ rewindLockSessionId.value = ''+ }+}+const sessionArtifacts = computed(() => collectSessionArtifacts(messagesList));// The panel already deleted the file server side; flag it in the loaded// history so the computed drops it without reloading the conversation.@@ -437,6 +556,11 @@ let recoverPollTimer = null;// the same "generating" typing indicator the normal reply path shows, so the wait// isn't a silent gap. IM-only: false everywhere else, so other flows are unchanged.const isImRecovering = ref(false);+const outgoingWorkBlocksRewind = computed(() => rewindBlockedByOutgoingWork({+ isReplying: isReplying.value,+ isStreaming: isStreaming.value,+ isRecovering: isImRecovering.value,+}))const scrollLock = ref(false);const isFirstEnter = ref(true);const loading = ref(false);@@ -892,7 +1016,10 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {if (historyLoadingMore.value || !hasMoreHistory.value) return;historyLoadingMore.value = true;}- fetchMessageList(data).then(async (res) => {+ return fetchMessageList(data).then(async (res) => {+ if (data?.session_id && String(data.session_id) !== String(session_id.value || '')) {+ return+ }const batch = res?.data;if (!batch?.length) {if (isScrollType) {@@ -960,6 +1087,7 @@ const findSteerQueueItem = (steerId) =>// Enter queues a follow-up; an explicit inject appears in the transcript immediately.const handleSteerMsg = async (value, mentionedItems = [], delivery = 'after', retryId = '') => {+ if (composerLocked.value) returnif (!session_id.value || !value?.trim()) return;if (!isReplying.value && !retryId) {// 空闲时没有运行中的 turn 可排队:直接走正常发送,而不是把@@ -1233,6 +1361,7 @@ const attachSteerFollowUp = async (completedAssistantId) => {};const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [], attachmentFiles = [], options = {}) => {+ if (composerLocked.value) returnstopStream();prepareForNewOutgoingMessage();activitySessionId.value = String(session_id.value);@@ -2008,3 +2137,16 @@ onBeforeRouteUpdate((to, from, next) => {opacity: 0;}</style>++<style lang="less">+.chat-rewind-popconfirm {+ max-width: 260px;++ .t-popconfirm__content,+ .t-popup__content {+ max-width: 260px;+ white-space: normal;+ line-height: 1.5;+ }+}+</style>diff --git a/frontend/src/views/chat/rewindNotice.test.ts b/frontend/src/views/chat/rewindNotice.test.tsnew file mode 100644index 000000000..60a37bbb8--- /dev/null+++ b/frontend/src/views/chat/rewindNotice.test.ts@@ -0,0 +1,23 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { rewindSkipMessage } from './rewindNotice'++const t = (key: string) => key++test('NO_SANDBOX maps to skipNoSandbox', () => {+ assert.equal(rewindSkipMessage('NO_SANDBOX', t), 'chat.rewind.skipNoSandbox')+})++test('NO_CHECKPOINT maps to skipNoCheckpoint', () => {+ assert.equal(rewindSkipMessage('NO_CHECKPOINT', t), 'chat.rewind.skipNoCheckpoint')+})++// A replaced sandbox fail-closes with a 409 rather than truncating, so it+// never arrives here as a skip reason.+test('unknown code falls back to generic skipped copy', () => {+ assert.equal(rewindSkipMessage('WEIRD', t), 'chat.rewind.skipped')+})++test('empty reason returns empty so the UI can skip the workspace notice', () => {+ assert.equal(rewindSkipMessage('', t), '')+})diff --git a/frontend/src/views/chat/rewindNotice.ts b/frontend/src/views/chat/rewindNotice.tsnew file mode 100644index 000000000..3d4370fb0--- /dev/null+++ b/frontend/src/views/chat/rewindNotice.ts@@ -0,0 +1,21 @@+/**+ * Maps a rewind skip reason from the API to i18n copy.+ *+ * An empty reason means the workspace was reset; the caller should not show+ * a skip notice in that case.+ */+export type RewindCopyFn = (key: string) => string++export function rewindSkipMessage(reason: string, t: RewindCopyFn): string {+ if (!reason) {+ return ''+ }+ switch (reason) {+ case 'NO_SANDBOX':+ return t('chat.rewind.skipNoSandbox')+ case 'NO_CHECKPOINT':+ return t('chat.rewind.skipNoCheckpoint')+ default:+ return t('chat.rewind.skipped')+ }+}diff --git a/frontend/src/views/chat/rewindView.test.ts b/frontend/src/views/chat/rewindView.test.tsnew file mode 100644index 000000000..3736fae16--- /dev/null+++ b/frontend/src/views/chat/rewindView.test.ts@@ -0,0 +1,110 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ canReplaceRewindTranscript,+ keepMessagesThroughRewindPoint,+ rewindableMessageIds,+ resolveRewindAffordance,+ rewindBlockedByOutgoingWork,+ rewindConflictI18nKey,+ rewindHistoryHasMore,+ rewindHttpConflictCode,+ rewindPrefillText,+ shouldApplyRewindLocally,+} from './rewindView'++test('applies rewind UI only while still on the source session', () => {+ assert.equal(shouldApplyRewindLocally('sess-1', 'sess-1'), true)+ assert.equal(shouldApplyRewindLocally('sess-2', 'sess-1'), false)+ assert.equal(shouldApplyRewindLocally('', 'sess-1'), false)+})++test('prefills only the user rewind point', () => {+ assert.equal(rewindPrefillText('user', 'rewrite this'), 'rewrite this')+ assert.equal(rewindPrefillText('assistant', 'keep this answer'), '')+ assert.equal(rewindPrefillText('user', undefined), '')+})++test('blocks rewind while a send, stream, or IM recover is in flight', () => {+ assert.equal(rewindBlockedByOutgoingWork({}), false)+ assert.equal(rewindBlockedByOutgoingWork({ isReplying: true }), true)+ assert.equal(rewindBlockedByOutgoingWork({ isStreaming: true }), true)+ assert.equal(rewindBlockedByOutgoingWork({ isRecovering: true }), true)+})++test('replaces the transcript only after a successful reload on the source session', () => {+ assert.equal(canReplaceRewindTranscript('sess-1', 'sess-1', undefined), true)+ assert.equal(canReplaceRewindTranscript('sess-1', 'sess-1', new Error('network')), false)+ assert.equal(canReplaceRewindTranscript('sess-2', 'sess-1', undefined), false)+})++test('history has more pages when the reload batch fills the limit', () => {+ assert.equal(rewindHistoryHasMore(20, 20), true)+ assert.equal(rewindHistoryHasMore(19, 20), false)+ assert.equal(rewindHistoryHasMore(0, 20), false)+})++test('keeps messages through an assistant rewind point and drops a user point', () => {+ const messages = [+ { id: 'u1', role: 'user' },+ { id: 'a1', role: 'assistant' },+ { id: 'u2', role: 'user' },+ { id: 'a2', role: 'assistant' },+ ]+ assert.deepEqual(+ keepMessagesThroughRewindPoint(messages, 'u2', 'user').map((m) => m.id),+ ['u1', 'a1'],+ )+ assert.deepEqual(+ keepMessagesThroughRewindPoint(messages, 'a1', 'assistant').map((m) => m.id),+ ['u1', 'a1'],+ )+})++test('offers rewind on user and assistant messages unless outgoing work or an incomplete turn', () => {+ const messages = [+ { id: 'u1', role: 'user' },+ { id: 'a1', role: 'assistant', is_completed: true },+ ]+ assert.equal(resolveRewindAffordance(messages, 'u1').canRewind, true)+ assert.equal(resolveRewindAffordance(messages, 'a1').canRewind, true)+ assert.equal(resolveRewindAffordance(messages, 'u1', { embeddedMode: true }).canRewind, false)+ assert.equal(resolveRewindAffordance(messages, 'u1', { outgoingWork: true }).canRewind, false)+ assert.equal(+ resolveRewindAffordance(+ [...messages, { id: 'a2', role: 'assistant', is_completed: false }],+ 'u1',+ ).canRewind,+ false,+ )+ assert.equal(resolveRewindAffordance(messages, 'sys', { }).canRewind, false)+})++test('maps rewind HTTP conflicts onto dedicated copy', () => {+ assert.equal(rewindHttpConflictCode({ status: 409, code: 'REWIND_NO_CHECKPOINT' }), 'REWIND_NO_CHECKPOINT')+ assert.equal(rewindHttpConflictCode({ $httpStatus: 409, code: 'REWIND_SOURCE_BUSY' }), 'REWIND_SOURCE_BUSY')+ assert.equal(rewindHttpConflictCode({ status: 500, code: 'REWIND_NO_CHECKPOINT' }), '')+ assert.equal(rewindConflictI18nKey('REWIND_NO_CHECKPOINT'), 'chat.rewind.noCheckpoint')+ assert.equal(rewindConflictI18nKey('REWIND_SANDBOX_REPLACED'), 'chat.rewind.sandboxReplaced')+ assert.equal(rewindConflictI18nKey('REWIND_SOURCE_BUSY'), 'chat.rewind.busy')+ assert.equal(rewindConflictI18nKey(''), 'chat.rewind.busy')+})++// The transcript resolves every row's control from this one set, so it has to+// answer exactly what the per-message check answers — and only walk once.+test('resolves every rewindable id in a single pass', () => {+ const messages = [+ { id: 'u1', role: 'user' },+ { id: 'a1', role: 'assistant', is_completed: true },+ { id: 'sys', role: 'system' },+ { id: '', role: 'user' },+ ]+ assert.deepEqual([...rewindableMessageIds(messages)], ['u1', 'a1'])+ assert.deepEqual([...rewindableMessageIds(messages, { embeddedMode: true })], [])+ assert.deepEqual([...rewindableMessageIds(messages, { outgoingWork: true })], [])+ assert.deepEqual(+ [...rewindableMessageIds([...messages, { id: 'a2', role: 'assistant', is_completed: false }])],+ [],+ 'an unfinished turn withdraws the control from the whole transcript',+ )+})diff --git a/frontend/src/views/chat/rewindView.ts b/frontend/src/views/chat/rewindView.tsnew file mode 100644index 000000000..dd52d245e--- /dev/null+++ b/frontend/src/views/chat/rewindView.ts@@ -0,0 +1,118 @@+/**+ * Client-side rewind helpers. The HTTP call mutates the source session on+ * the server; these decide whether that result may touch the live chat view.+ */++export function shouldApplyRewindLocally(currentSessionId: string, sourceSessionId: string): boolean {+ return Boolean(currentSessionId) && currentSessionId === sourceSessionId+}++export function rewindPrefillText(role: unknown, content: unknown): string {+ if (role !== 'user') {+ return ''+ }+ return String(content ?? '')+}++export function rewindBlockedByOutgoingWork(state: {+ isReplying?: boolean+ isStreaming?: boolean+ isRecovering?: boolean+}): boolean {+ return Boolean(state.isReplying || state.isStreaming || state.isRecovering)+}++/** Empty history is success (the conversation was cleared). A thrown reload is not. */+export function canReplaceRewindTranscript(+ currentSessionId: string,+ sourceSessionId: string,+ reloadError: unknown,+): boolean {+ if (reloadError) {+ return false+ }+ return shouldApplyRewindLocally(currentSessionId, sourceSessionId)+}++export function rewindHistoryHasMore(batchLength: number, limit: number): boolean {+ return batchLength >= limit+}++export function keepMessagesThroughRewindPoint<T extends { id?: unknown }>(+ messages: T[],+ messageId: string,+ role: unknown,+ isMatch: (message: T) => boolean = (message) => String(message.id || '') === messageId,+): T[] {+ const index = messages.findIndex(isMatch)+ if (index < 0) {+ return messages+ }+ if (role === 'user') {+ return messages.slice(0, index)+ }+ return messages.slice(0, index + 1)+}++export interface RewindCandidateMessage {+ id?: unknown+ role?: unknown+ is_completed?: unknown+}++export function resolveRewindAffordance(+ messages: RewindCandidateMessage[],+ messageId: string,+ opts: { embeddedMode?: boolean; outgoingWork?: boolean } = {},+): { canRewind: boolean } {+ return { canRewind: rewindableMessageIds(messages, opts).has(messageId) }+}++/**+ * The ids a rewind control may be offered on, resolved in one pass.+ *+ * The transcript asks this per rendered message and re-asks on every streamed+ * token, so the whole-list conditions (is any turn still generating?) are+ * hoisted out of the per-message check instead of rescanning for each row.+ */+export function rewindableMessageIds(+ messages: RewindCandidateMessage[],+ opts: { embeddedMode?: boolean; outgoingWork?: boolean } = {},+): Set<string> {+ const ids = new Set<string>()+ if (opts.embeddedMode || opts.outgoingWork) {+ return ids+ }+ for (const message of messages) {+ if (message.role === 'assistant' && message.is_completed === false) {+ return new Set<string>()+ }+ const id = String(message.id || '')+ if (id && (message.role === 'assistant' || message.role === 'user')) {+ ids.add(id)+ }+ }+ return ids+}++export function rewindHttpConflictCode(err: unknown): string {+ if (!err || typeof err !== 'object') {+ return ''+ }+ const rec = err as { code?: unknown; status?: unknown; $httpStatus?: unknown }+ const status = rec.status ?? rec.$httpStatus+ if (status !== 409) {+ return ''+ }+ return typeof rec.code === 'string' ? rec.code : ''+}++export function rewindConflictI18nKey(code: string): string {+ if (code === 'REWIND_NO_CHECKPOINT') {+ return 'chat.rewind.noCheckpoint'+ }+ if (code === 'REWIND_SANDBOX_REPLACED') {+ return 'chat.rewind.sandboxReplaced'+ }+ return 'chat.rewind.busy'+}diff --git a/frontend/src/views/chat/steerInteraction.test.mjs b/frontend/src/views/chat/steerInteraction.test.mjsindex ff1f046b3..da6f6e6bb 100644--- a/frontend/src/views/chat/steerInteraction.test.mjs+++ b/frontend/src/views/chat/steerInteraction.test.mjs@@ -19,6 +19,7 @@ function harness(overrides = {}) {const state = {session_id: { value: 'session' }, currentAssistantMessageId: { value: 'assistant' },isReplying: { value: true }, isStreaming: { value: true },+ composerLocked: { value: false },steerQueue: { value: [] }, messagesList: reactive([]), crypto: webcrypto, makeSteerClientId,previewSteerMessage, discardSteerPreview, reconcileSteerMessageId,scrollToBottom() {}, sendMsg() { throw new Error('must not start a second run') },@@ -29,6 +30,17 @@ function harness(overrides = {}) {return { ...actions, state }}+test('locked composer drops a steer without touching the queue', async () => {+ let called = 0+ const h = harness({+ composerLocked: { value: true },+ steerSession: async () => { called += 1; return { status: 'queued' } },+ })+ await h.handleSteerMsg('queued')+ assert.equal(called, 0)+ assert.equal(h.state.steerQueue.value.length, 0)+})+test('default after stays below; promotion immediately moves it into the transcript', async () => {const request = deferred(), promote = deferred()const h = harness({ steerSession: () => request.promise, promoteSteerSession: () => promote.promise })diff --git a/internal/application/repository/message.go b/internal/application/repository/message.goindex 465552151..1adef0851 100644--- a/internal/application/repository/message.go+++ b/internal/application/repository/message.go@@ -106,6 +106,27 @@ func (r *messageRepository) GetRecentMessagesBySession(return messages, nil}+// SessionHasIncompleteAssistant reports whether any assistant message in the+// session is still generating. Rewind uses this instead of paging oldest+// messages, so a late incomplete turn is not hidden behind a 1000-row window.+func (r *messageRepository) SessionHasIncompleteAssistant(+ ctx context.Context, sessionID string,+) (bool, error) {+ if sessionID == "" {+ return false, nil+ }+ var id string+ err := r.db.WithContext(ctx).Model(&types.Message{}).+ Select("id").+ Where("session_id = ? AND role = ? AND is_completed = ?", sessionID, "assistant", false).+ Limit(1).+ Scan(&id).Error+ if err != nil {+ return false, err+ }+ return id != "", nil+}+// GetMessagesBySessionBeforeTime retrieves messages from a session created before a specific timefunc (r *messageRepository) GetMessagesBySessionBeforeTime(ctx context.Context, sessionID string, beforeTime time.Time, limit int,@@ -213,6 +234,30 @@ func (r *messageRepository) ListMessagesBySessionUpTo(return messages, nil}+// ListAssistantCheckpointsUpTo returns the assistant messages strictly before+// the (boundary, boundaryID) cursor, oldest first, carrying only the columns+// that identify a workspace checkpoint.+//+// Rewind asks "does kept history still reach a commit SHA, and did it contain+// an assistant turn at all". ListMessagesBySessionUpTo can answer that, but it+// selects every column and joins artifacts for the whole conversation to do+// so. This is the same question against a fraction of the rows and bytes.+func (r *messageRepository) ListAssistantCheckpointsUpTo(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string,+) ([]*types.Message, error) {+ var messages []*types.Message+ if err := r.db.WithContext(ctx).+ Model(&types.Message{}).+ Select("id", "session_id", "role", "created_at", "sandbox_checkpoint").+ Where("session_id = ? AND role = ?", sessionID, "assistant").+ Where("created_at < ? OR (created_at = ? AND id < ?)", boundary, boundary, boundaryID).+ Order("created_at ASC, id ASC").+ Find(&messages).Error; err != nil {+ return nil, err+ }+ return messages, nil+}+// UpdateMessage updates an existing message. Artifacts are rewritten only// when message.Artifacts is non-nil (see writeMessageArtifacts).func (r *messageRepository) UpdateMessage(ctx context.Context, message *types.Message) error {@@ -226,6 +271,48 @@ func (r *messageRepository) UpdateMessage(ctx context.Context, message *types.Me})}+// DeleteMessagesFrom soft-deletes every message of a session at or after the+// (boundary, boundaryID) composite cursor and returns the deleted rows, oldest+// first, so the caller can clean up what hangs off them.+//+// inclusive selects the rewind semantics: a user rewind point is dropped along+// with everything after it (the client prefills that question back into the+// composer), while an assistant rewind point survives and the conversation+// resumes after it. The cursor is composite for the same reason+// ListMessagesBySessionUpTo is — two messages written in the same millisecond+// are ordered by ID, so the cut is reproducible.+//+// The read and the delete share one transaction: the returned rows must be+// exactly the rows that went away, or the cleanup that follows would act on a+// different set than the conversation lost.+func (r *messageRepository) DeleteMessagesFrom(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string, inclusive bool,+) ([]*types.Message, error) {+ condition := "created_at > ? OR (created_at = ? AND id > ?)"+ if inclusive {+ condition = "created_at > ? OR (created_at = ? AND id >= ?)"+ }++ var deleted []*types.Message+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ scope := func() *gorm.DB {+ return tx.Where("session_id = ?", sessionID).+ Where(condition, boundary, boundary, boundaryID)+ }+ if err := scope().Order("created_at ASC, id ASC").Find(&deleted).Error; err != nil {+ return err+ }+ if len(deleted) == 0 {+ return nil+ }+ return scope().Delete(&types.Message{}).Error+ })+ if err != nil {+ return nil, err+ }+ return deleted, nil+}+// DeleteMessage deletes a messagefunc (r *messageRepository) DeleteMessage(ctx context.Context, sessionID string, messageID string) error {return r.db.WithContext(ctx).Where(diff --git a/internal/application/repository/message_artifact.go b/internal/application/repository/message_artifact.goindex bce79c26b..19016a4fe 100644--- a/internal/application/repository/message_artifact.go+++ b/internal/application/repository/message_artifact.go@@ -187,6 +187,25 @@ func (r *messageRepository) GetSessionArtifacts(return result, nil}+// ListLiveArtifactsByMessageIDs returns undeleted artifact rows for the given+// messages. It does not join messages, so rewind can tombstone files after+// those messages have already been soft-deleted.+func (r *messageRepository) ListLiveArtifactsByMessageIDs(+ ctx context.Context, sessionID string, messageIDs []string,+) ([]types.MessageArtifactRecord, error) {+ if sessionID == "" || len(messageIDs) == 0 {+ return nil, nil+ }+ var rows []types.MessageArtifactRecord+ if err := r.db.WithContext(ctx).+ Where("session_id = ? AND message_id IN ? AND deleted_at IS NULL", sessionID, messageIDs).+ Order("message_id ASC, position ASC").+ Find(&rows).Error; err != nil {+ return nil, err+ }+ return rows, nil+}+// RecordRestoredArtifactMtime stamps a same-content sandbox restore's mtime// onto this session's artifacts at sourcePath whose content already hashed to// hash, mirroring MessageArtifacts.WithRestoredMtime: other versions at thediff --git a/internal/application/repository/message_rewind_boundary_test.go b/internal/application/repository/message_rewind_boundary_test.gonew file mode 100644index 000000000..cfb5a41ed--- /dev/null+++ b/internal/application/repository/message_rewind_boundary_test.go@@ -0,0 +1,160 @@+package repository++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm"+)++// Rewinding at a user message drops that question too, so the boundary itself+// is deleted and the caller can prefill it back into the composer.+func TestDeleteMessagesFromInclusiveDropsBoundaryAndLater(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)++ seedMessage(t, db, "m1", "s1", "user", base)+ seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))+ seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))+ seedMessage(t, db, "m4", "s1", "assistant", base.Add(3*time.Second))++ deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base.Add(2*time.Second), "m3", true)+ require.NoError(t, err)+ require.Equal(t, []string{"m3", "m4"}, messageIDs(deleted))++ require.Equal(t, []string{"m1", "m2"}, remainingMessageIDs(t, db, "s1"))+}++// Rewinding at an assistant answer keeps that answer: the conversation resumes+// right after it.+func TestDeleteMessagesFromExclusiveKeepsBoundary(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)++ seedMessage(t, db, "m1", "s1", "user", base)+ seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))+ seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))++ deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base.Add(time.Second), "m2", false)+ require.NoError(t, err)+ require.Equal(t, []string{"m3"}, messageIDs(deleted))++ require.Equal(t, []string{"m1", "m2"}, remainingMessageIDs(t, db, "s1"))+}++// Same-millisecond peers are ordered by ID, so the cut is reproducible.+func TestDeleteMessagesFromUsesCompositeCursor(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ at := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)++ seedMessage(t, db, "m-a", "s1", "user", at)+ seedMessage(t, db, "m-b", "s1", "assistant", at)+ seedMessage(t, db, "m-c", "s1", "user", at)++ deleted, err := repo.DeleteMessagesFrom(ctx, "s1", at, "m-b", true)+ require.NoError(t, err)+ require.Equal(t, []string{"m-b", "m-c"}, messageIDs(deleted))+ require.Equal(t, []string{"m-a"}, remainingMessageIDs(t, db, "s1"))+}++func TestDeleteMessagesFromLeavesOtherSessionsAlone(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)++ seedMessage(t, db, "mine", "s1", "user", base)+ seedMessage(t, db, "theirs", "s2", "user", base.Add(time.Second))++ deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base, "mine", true)+ require.NoError(t, err)+ require.Equal(t, []string{"mine"}, messageIDs(deleted))+ require.Equal(t, []string{"theirs"}, remainingMessageIDs(t, db, "s2"))+}++func TestDeleteMessagesFromReportsNothingWhenAlreadyAtTheEnd(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ base := time.Date(2026, 9, 17, 9, 0, 0, 0, time.UTC)++ seedMessage(t, db, "m1", "s1", "user", base)+ seedMessage(t, db, "m2", "s1", "assistant", base.Add(time.Second))++ deleted, err := repo.DeleteMessagesFrom(ctx, "s1", base.Add(time.Second), "m2", false)+ require.NoError(t, err)+ require.Empty(t, deleted)+ require.Equal(t, []string{"m1", "m2"}, remainingMessageIDs(t, db, "s1"))+}++func remainingMessageIDs(t *testing.T, db *gorm.DB, sessionID string) []string {+ t.Helper()+ var rows []*types.Message+ require.NoError(t, db.Where("session_id = ?", sessionID).+ Order("created_at ASC, id ASC").Find(&rows).Error)+ return messageIDs(rows)+}++// The cheap checkpoint lookup must agree with the full-history read rewind+// used to do, or the two paths would disagree about which SHA survives a cut.+func TestListAssistantCheckpointsUpToMatchesFullHistoryPrefix(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)++ seedMessage(t, db, "m1", "s1", "user", base)+ seedCheckpointMessage(t, db, "m2", "s1", base.Add(time.Second), "sb1", strings.Repeat("a", 40))+ seedMessage(t, db, "m3", "s1", "user", base.Add(2*time.Second))+ seedCheckpointMessage(t, db, "m4", "s1", base.Add(3*time.Second), "sb1", strings.Repeat("b", 40))+ seedMessage(t, db, "boundary", "s1", "user", base.Add(4*time.Second))+ seedCheckpointMessage(t, db, "later", "s1", base.Add(5*time.Second), "sb1", strings.Repeat("c", 40))+ seedCheckpointMessage(t, db, "other", "s2", base, "sb2", strings.Repeat("d", 40))++ got, err := repo.ListAssistantCheckpointsUpTo(ctx, "s1", base.Add(4*time.Second), "boundary")+ require.NoError(t, err)+ require.Equal(t, []string{"m2", "m4"}, messageIDs(got))+ require.NotNil(t, got[1].SandboxCheckpoint)+ require.Equal(t, strings.Repeat("b", 40), got[1].SandboxCheckpoint.CommitSHA)+ require.Equal(t, "sb1", got[1].SandboxCheckpoint.SandboxID)++ full, err := repo.ListMessagesBySessionUpTo(ctx, "s1", base.Add(4*time.Second), "boundary")+ require.NoError(t, err)+ require.Equal(t, []string{"m1", "m2", "m3", "m4"}, messageIDs(full))+}++func TestListAssistantCheckpointsUpToSkipsSoftDeleted(t *testing.T) {+ repo, db := newMessageRepositoryForForkTest(t)+ ctx := context.Background()+ base := time.Date(2026, 9, 10, 9, 0, 0, 0, time.UTC)++ seedCheckpointMessage(t, db, "m1", "s1", base, "sb1", strings.Repeat("a", 40))+ seedCheckpointMessage(t, db, "m2", "s1", base.Add(time.Second), "sb1", strings.Repeat("b", 40))+ seedMessage(t, db, "boundary", "s1", "user", base.Add(2*time.Second))+ require.NoError(t, db.Delete(&types.Message{}, "id = ?", "m2").Error)++ got, err := repo.ListAssistantCheckpointsUpTo(ctx, "s1", base.Add(2*time.Second), "boundary")+ require.NoError(t, err)+ require.Equal(t, []string{"m1"}, messageIDs(got))+}++func seedCheckpointMessage(+ t *testing.T, db *gorm.DB, id, sessionID string, at time.Time, sandboxID, sha string,+) {+ t.Helper()+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{+ ID: id,+ SessionID: sessionID,+ Role: "assistant",+ Content: "answer body that the checkpoint query must not need to read",+ CreatedAt: at,+ SandboxCheckpoint: &types.SandboxCheckpoint{+ SandboxID: sandboxID,+ CommitSHA: sha,+ },+ }).Error)+}diff --git a/internal/application/repository/message_suggestion.go b/internal/application/repository/message_suggestion.goindex 73c281cb1..96e255e17 100644--- a/internal/application/repository/message_suggestion.go+++ b/internal/application/repository/message_suggestion.go@@ -160,6 +160,23 @@ func (r *messageSuggestionRepository) DeleteByMessageID(Delete(&types.MessageSuggestionSet{}).Error}+// DeleteByMessageIDs is the batch form of DeleteByMessageID. Rewind drops a+// whole tail of the conversation at once and would otherwise issue one round+// trip per deleted message while holding the rewind lock.+func (r *messageSuggestionRepository) DeleteByMessageIDs(+ ctx context.Context,+ tenantID uint64,+ sessionID string,+ messageIDs []string,+) error {+ if len(messageIDs) == 0 {+ return nil+ }+ return r.db.WithContext(ctx).+ Where("tenant_id = ? AND session_id = ? AND assistant_message_id IN ?", tenantID, sessionID, messageIDs).+ Delete(&types.MessageSuggestionSet{}).Error+}+func (r *messageSuggestionRepository) DeleteBySessionID(ctx context.Context,tenantID uint64,diff --git a/internal/application/service/fork_bootstrapper.go b/internal/application/service/fork_bootstrapper.goindex 29b90a308..af5723b40 100644--- a/internal/application/service/fork_bootstrapper.go+++ b/internal/application/service/fork_bootstrapper.go@@ -20,7 +20,6 @@ package serviceimport ("context"- "errors""fmt""strings""time"@@ -46,11 +45,6 @@ type forkBootstrapMessageStore interface {RewriteSandboxCheckpoints(ctx context.Context, sessionID, oldSandboxID, newSandboxID string) error}-// forkResetTimeout bounds the git rollback. clean -fdx may delete a large-// untracked tree, and gc --prune=now walks leftover objects from later turns,-// so this is more generous than the per-turn checkpoint.-const forkResetTimeout = 90 * time.Second-// ForkBootstrapper provisions forked sessions' first sandbox.type ForkBootstrapper struct {sessions forkBootstrapSessionStore@@ -223,76 +217,35 @@ func (b *ForkBootstrapper) snapshotStillShared(ctx context.Context, sessionID, sreturn b.sessions.HasOtherUnconsumedForkSnapshot(ctx, snapshotID, sessionID)}-func forkResetScript(workspace, sha string) (string, error) {- if !gitSHAPattern.MatchString(sha) {- return "", fmt.Errorf("fork bootstrap: invalid commit sha %q", truncateForLog(sha))- }- ws := shellSingleQuote(workspace)- return fmt.Sprintf(`set -e-git config --global safe.directory %[1]s-git -C %[1]s reset --hard %[2]s-current=$(git -C %[1]s symbolic-ref -q HEAD || true)-for ref in $(git -C %[1]s for-each-ref --format='%%(refname)'); do- [ -z "$ref" ] && continue- [ "$ref" = "$current" ] && continue- git -C %[1]s update-ref -d "$ref"-done-rm -f %[1]s/.git/ORIG_HEAD %[1]s/.git/FETCH_HEAD-git -C %[1]s reflog expire --expire=now --all-git -C %[1]s gc --prune=now-git -C %[1]s clean -fdx`, ws, sha), nil-}--func shellSingleQuote(s string) string {- return "'" + strings.ReplaceAll(s, `'`, `'"'"'`) + "'"-}--func gitResetFailure(sha, stderr string) error {- return fmt.Errorf("fork bootstrap: git reset to %s failed: %s", sha, stderr)-}-// resetWorkspace rolls /workspace back to sha.//-// reset --hard restores tracked files (including input/ and output/). Other-// refs, ORIG_HEAD, and reflogs still name later-turn commits from the live-// snapshot, so those are deleted and gc'd before clean -fdx; otherwise the-// working tree would look right while `git checkout` could resurrect later-// files. -x then drops leftover untracked files that are not in that commit.+// AfterCreate runs under the session lifecycle lock and already holds the+// handle Create returned, so the client path execs directly rather than going+// through the runner, which would Resolve. Deployments without a client fall+// back to the shared runner helper.func (b *ForkBootstrapper) resetWorkspace(ctx context.Context, sessionID, sha string, handle sandbox.RemoteSandboxHandle,) error {- script, err := forkResetScript(sandbox.SessionWorkspaceRoot, strings.TrimSpace(sha))- if err != nil {- return err- }-- if b.client != nil && handle != nil {- result, err := b.client.Exec(ctx, handle, sandbox.RemoteExecRequest{- Command: script,- Shell: true,- WorkDir: sandbox.SessionWorkspaceRoot,- Timeout: forkResetTimeout,- User: sandbox.DefaultSandboxExecUser,- })- if err != nil {- return fmt.Errorf("fork bootstrap: git reset exec: %w", err)+ sha = strings.TrimSpace(sha)+ if b.client == nil || handle == nil {+ expectedID := ""+ if handle != nil {+ expectedID = handle.ID()}- if result == nil || result.ExitCode != 0 {- stderr := ""- if result != nil {- stderr = result.Stderr- }- return gitResetFailure(sha, stderr)- }- return nil+ return resetWorkspaceToCommit(ctx, b.runner, sessionID, sha, expectedID)}- if b.runner == nil {- return errors.New("fork bootstrap: no shell runner wired")+ script, err := workspaceResetScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, sha)+ if err != nil {+ return err}- result, err := b.runner.ExecShellCommand(- ctx, sessionID, script, sandbox.SessionWorkspaceRoot, forkResetTimeout, nil,- )+ result, err := b.client.Exec(ctx, handle, sandbox.RemoteExecRequest{+ Command: script,+ Shell: true,+ WorkDir: sandbox.SessionWorkspaceRoot,+ Timeout: workspaceResetTimeout,+ User: sandbox.DefaultSandboxExecUser,+ })if err != nil {return fmt.Errorf("fork bootstrap: git reset exec: %w", err)}diff --git a/internal/application/service/fork_bootstrapper_test.go b/internal/application/service/fork_bootstrapper_test.goindex 2c5ccf9a6..d63d08c82 100644--- a/internal/application/service/fork_bootstrapper_test.go+++ b/internal/application/service/fork_bootstrapper_test.go@@ -4,7 +4,6 @@ import ("context""errors""os"- "os/exec""path/filepath""strings""testing"@@ -109,6 +108,7 @@ func TestAfterCreateResetsWorkspaceThenConsumesAndDeletesSnapshot(t *testing.T)require.Contains(t, script, "gc --prune=now")require.Contains(t, script, "clean -fdx")require.Contains(t, script, "ORIG_HEAD")+ assertWorkspaceGitLayout(t, script)require.Equal(t, []string{"snap-1"}, snapshots.deleted)require.NotNil(t, sessions.updatedBootstrap)@@ -263,71 +263,14 @@ func TestAfterCreateRejectsInvalidCommitSHAWithoutExec(t *testing.T) {}func TestForkResetScriptRejectsNonHexSHA(t *testing.T) {- _, err := forkResetScript(sandbox.SessionWorkspaceRoot, "abc123")+ _, err := workspaceResetScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, "abc123")require.Error(t, err)- _, err = forkResetScript(sandbox.SessionWorkspaceRoot, "")+ _, err = workspaceResetScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, "")require.Error(t, err)- _, err = forkResetScript(sandbox.SessionWorkspaceRoot, forkTestCommitSHA()+";rm")+ _, err = workspaceResetScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, forkTestCommitSHA()+";rm")require.Error(t, err)}-func TestForkResetScriptPrunesLaterCommits(t *testing.T) {- if _, err := exec.LookPath("git"); err != nil {- t.Skip("git not available")- }- dir := t.TempDir()- // Git hooks export repository overrides. Use disposable paths to reproduce- // that environment without risking the repository running this test.- inheritedRepo := t.TempDir()- t.Setenv("GIT_DIR", filepath.Join(inheritedRepo, "repo.git"))- t.Setenv("GIT_WORK_TREE", inheritedRepo)- t.Setenv("GIT_INDEX_FILE", filepath.Join(inheritedRepo, "index"))- env := isolatedGitEnv(t)- runGit := func(args ...string) string {- t.Helper()- cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)- cmd.Env = env- out, err := cmd.CombinedOutput()- require.NoError(t, err, string(out))- return strings.TrimSpace(string(out))- }-- runGit("init")- _, err := os.Stat(filepath.Join(dir, ".git"))- require.NoError(t, err, "git init must use the test directory")- runGit("config", "user.email", "[email protected]")- runGit("config", "user.name", "WeKnora Agent")- require.NoError(t, os.WriteFile(filepath.Join(dir, "keep.txt"), []byte("early"), 0o644))- runGit("add", "-A")- runGit("commit", "-m", "early")- early := runGit("rev-parse", "HEAD")- if !gitSHAPattern.MatchString(early) {- t.Skip("host git is not using SHA-1 object names")- }-- require.NoError(t, os.WriteFile(filepath.Join(dir, "secret.txt"), []byte("later-secret"), 0o644))- runGit("add", "-A")- runGit("commit", "-m", "later")- later := runGit("rev-parse", "HEAD")- require.NotEqual(t, early, later)-- script, err := forkResetScript(dir, early)- require.NoError(t, err)- cmd := exec.Command("bash", "-c", script)- cmd.Env = env- out, err := cmd.CombinedOutput()- require.NoError(t, err, string(out))-- cat := exec.Command("git", "-C", dir, "cat-file", "-t", later)- cat.Env = env- require.Error(t, cat.Run(), "later-turn commit must be unreachable after prune")- _, err = os.Stat(filepath.Join(dir, "secret.txt"))- require.True(t, os.IsNotExist(err))- body, err := os.ReadFile(filepath.Join(dir, "keep.txt"))- require.NoError(t, err)- require.Equal(t, "early", string(body))-}-func isolatedGitEnv(t *testing.T) []string {t.Helper()// Neither the temporary repository commands nor the reset script may@@ -432,9 +375,10 @@ func TestAfterCreateWithClientUsesHandleNotRunner(t *testing.T) {require.True(t, client.execs[0].Shell)require.Equal(t, sandbox.SessionWorkspaceRoot, client.execs[0].WorkDir)require.Equal(t, sandbox.DefaultSandboxExecUser, client.execs[0].User)- require.Equal(t, forkResetTimeout, client.execs[0].Timeout)+ require.Equal(t, workspaceResetTimeout, client.execs[0].Timeout)require.Contains(t, client.execs[0].Command, "reset --hard "+forkTestCommitSHA())require.Contains(t, client.execs[0].Command, "gc --prune=now")+ assertWorkspaceGitLayout(t, client.execs[0].Command)require.Equal(t, []string{"snap-1"}, snapshots.deleted)require.True(t, sessions.updatedBootstrap.Consumed())}diff --git a/internal/application/service/pinned_session_sandbox.go b/internal/application/service/pinned_session_sandbox.goindex 7bb69a3fd..fa2ac3778 100644--- a/internal/application/service/pinned_session_sandbox.go+++ b/internal/application/service/pinned_session_sandbox.go@@ -118,6 +118,32 @@ func (a *PinnedSessionSandbox) HasActiveTurn(ctx context.Context, sessionID strireturn false, nil}+// TryLockRewind takes an exclusive rewind lock through the session's pinned+// manager. Managers that do not expose the method succeed as a no-op.+func (a *PinnedSessionSandbox) TryLockRewind(ctx context.Context, sessionID string) (func(), error) {+ mgr := a.manager(ctx, sessionID)+ type locker interface {+ TryLockRewind(context.Context, string) (func(), error)+ }+ if l, ok := mgr.(locker); ok {+ return l.TryLockRewind(ctx, sessionID)+ }+ return func() {}, nil+}++// HasRewindLock reports whether rewind currently holds the session on the+// pinned manager. Managers that do not expose the method are treated as free.+func (a *PinnedSessionSandbox) HasRewindLock(ctx context.Context, sessionID string) (bool, error) {+ mgr := a.manager(ctx, sessionID)+ type rewindLockReader interface {+ HasRewindLock(context.Context, string) (bool, error)+ }+ if reader, ok := mgr.(rewindLockReader); ok {+ return reader.HasRewindLock(ctx, sessionID)+ }+ return false, nil+}+// CreateForkSnapshot snapshots the session's already-bound sandbox through the// pinned manager. Managers that do not expose the method return an error so// fork can degrade to SNAPSHOT_UNSUPPORTED.@@ -160,4 +186,8 @@ var _ SandboxShellRunner = (*PinnedSessionSandbox)(nil)var _ SessionForkSandboxPort = (*PinnedSessionSandbox)(nil)+var _ SessionRewindSandboxPort = (*PinnedSessionSandbox)(nil)+var _ SessionForkSandboxPort = (*sandbox.SessionBoundManager)(nil)++var _ SessionRewindSandboxPort = (*sandbox.SessionBoundManager)(nil)diff --git a/internal/application/service/sandbox_operation_requests_test.go b/internal/application/service/sandbox_operation_requests_test.goindex 234f6d670..06980b97a 100644--- a/internal/application/service/sandbox_operation_requests_test.go+++ b/internal/application/service/sandbox_operation_requests_test.go@@ -157,9 +157,40 @@ func TestPinnedCheckpointSkipsWorkspacePreparation(t *testing.T) {require.NotNil(t, checkpoint)require.Equal(t, "sb1", checkpoint.SandboxID)require.Equal(t, strings.Repeat("a", 40), checkpoint.CommitSHA)- require.Equal(t, []string{"connect", "exec"}, client.ops)+ require.Equal(t, []string{"connect", "exec"}, client.ops,+ "SkipWorkspacePrep must omit the extra prepareSessionDirs exec")require.Equal(t, workspaceCheckpointTimeout, client.exec.Timeout)require.Equal(t, sandbox.SessionWorkspaceRoot, client.exec.WorkDir)require.Contains(t, client.exec.Command, "--allow-empty")- require.NotContains(t, client.exec.Command, "mkdir")+ require.Contains(t, client.exec.Command, sandbox.SessionGitDir)+ require.Contains(t, client.exec.Command, `mkdir -p "$WORK_TREE"`)+ require.NotContains(t, client.exec.Command, `mkdir -p -- "$d"`,+ "checkpoint must not run the session input/output bootstrap")+}++func TestPinnedRewindResetSkipsWorkspacePreparation(t *testing.T) {+ ctx, mgr, client := newOperationRequestManager(t)+ pinned := NewPinnedSessionSandbox(stubPinReader{configID: "cfg1"}, &stubTenantSandboxResolver{mgr: mgr}, nil)+ sha := strings.Repeat("a", 40)+ require.NoError(t, resetWorkspaceToCommit(ctx, pinned, "s1", sha, "sb1"))+ require.Equal(t, []string{"connect", "exec"}, client.ops,+ "SkipWorkspacePrep must omit the extra prepareSessionDirs exec")+ require.Equal(t, workspaceResetTimeout, client.exec.Timeout)+ require.Equal(t, sandbox.SessionWorkspaceRoot, client.exec.WorkDir)+ require.Contains(t, client.exec.Command, "reset --hard "+sha)+ require.NotContains(t, client.exec.Command, `mkdir -p -- "$d"`)+}++func TestPinnedEmptyResetSkipsWorkspacePreparation(t *testing.T) {+ ctx, mgr, client := newOperationRequestManager(t)+ pinned := NewPinnedSessionSandbox(stubPinReader{configID: "cfg1"}, &stubTenantSandboxResolver{mgr: mgr}, nil)+ require.NoError(t, resetWorkspaceToEmpty(ctx, pinned, "s1", "sb1"))+ require.Equal(t, []string{"connect", "exec"}, client.ops,+ "SkipWorkspacePrep must omit the extra prepareSessionDirs exec")+ require.Contains(t, client.exec.Command, "commit-tree")+ require.Contains(t, client.exec.Command, "reset --hard")+ require.Contains(t, client.exec.Command, "clean -fdx")+ require.NotContains(t, client.exec.Command, `rm -rf "$GIT_DIR"`)+ require.NotContains(t, client.exec.Command, `find "$WORK_TREE"`)+ require.NotContains(t, client.exec.Command, `mkdir -p -- "$d"`)}diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex 4c5583ca2..c59a7d5ef 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -138,6 +138,7 @@ type sessionService struct {// before its sandbox is provisioned. Nil uses NewResolverForkSnapshotDeleter// from sandboxResolver/sandboxMgr.forkSnapshots ForkSnapshotDeleter+ busyGate *SessionBusyGate}// NewSessionService creates a new session service instance with all required dependencies@@ -162,6 +163,7 @@ func NewSessionService(cfg *config.Config,memoryService interfaces.MemoryService,sandboxConfigRepo repository.TenantSandboxConfigRepository,tenantSkillRepo repository.TenantSkillRepository,+ busyGate *SessionBusyGate,) interfaces.SessionService {return &sessionService{cfg: cfg,@@ -185,6 +187,7 @@ func NewSessionService(cfg *config.Config,memoryService: memoryService,sandboxConfigRepo: sandboxConfigRepo,tenantSkillRepo: tenantSkillRepo,+ busyGate: busyGate,}}@@ -980,38 +983,59 @@ func (s *sessionService) GenerateTitleAsync(// a skill-image change mid-turn cannot rebuild the VM between tool calls.// The first resolve of this turn may still pick up a stale mark from the// previous turn. The returned closer must be called.+//+// A rewind in progress is a hard failure: the agent must not start on a+// workspace that git reset is about to rewrite. Every other lease error+// degrades to "no lease" and lets the turn run, as it did before rewind+// existed — a Redis blip on the lease script must not reject the user's+// message, and rewind reads the same Redis to decide it is busy, so it+// cannot silently proceed while this store is unreachable either.func (s *sessionService) holdSandboxTurn(ctx context.Context, sessionID, configID string,-) func() {+) (func(), error) {+ noop := func() {}if strings.TrimSpace(sessionID) == "" {- return func() {}+ return noop, nil+ }+ releaseGate, err := s.busyGate.HoldSend(sessionID)+ if err != nil {+ return noop, err}- begin := func(mgr sandbox.Manager) sandbox.SessionTurnHolder {+ begin := func(mgr sandbox.Manager) (sandbox.SessionTurnHolder, error) {if mgr == nil {- return nil+ return nil, nil}holder, ok := mgr.(sandbox.SessionTurnHolder)if !ok {- return nil+ return nil, nil}if err := holder.BeginSessionTurn(ctx, sessionID); err != nil {logger.Warnf(ctx, "[sandbox] begin turn for session %s failed: %v", sessionID, err)- return nil+ if stderrors.Is(err, sandbox.ErrSessionRewindLocked) {+ return nil, err+ }+ return nil, nil}- return holder+ return holder, nil}- if holder := begin(s.sandboxMgr); holder != nil {+ holder, err := begin(s.sandboxMgr)+ if err != nil {+ releaseGate()+ return noop, err+ }+ if holder != nil {return func() {if err := holder.EndSessionTurn(ctx, sessionID); err != nil {logger.Warnf(ctx, "[sandbox] end turn for session %s failed: %v", sessionID, err)}- }+ releaseGate()+ }, nil}tenantID, _ := types.TenantIDFromContext(ctx)if s.sandboxResolver == nil || tenantID == 0 {- return func() {}+ return releaseGate, nil}mgr, err := resolveTenantSandboxForConfig(ctx, s.sandboxResolver, s.sandboxMgr, tenantID, configID, s.sandboxPolicy,@@ -1019,15 +1043,61 @@ func (s *sessionService) holdSandboxTurn(if err != nil {logger.Warnf(ctx, "[sandbox] resolve config %s to begin turn of session %s failed: %v",configID, sessionID, err)- return func() {}+ return releaseGate, nil+ }+ holder, err = begin(mgr)+ if err != nil {+ releaseGate()+ return noop, err}- holder := begin(mgr)if holder == nil {- return func() {}+ return releaseGate, nil}return func() {if err := holder.EndSessionTurn(ctx, sessionID); err != nil {logger.Warnf(ctx, "[sandbox] end turn for session %s failed: %v", sessionID, err)}+ releaseGate()+ }, nil+}++// RejectSendIfRewinding fails when rewind currently holds sessionID, so+// knowledge-chat (no sandbox turn lease) cannot persist a new turn on a+// session that is about to delete those messages.+func (s *sessionService) RejectSendIfRewinding(ctx context.Context, sessionID string) error {+ if strings.TrimSpace(sessionID) == "" {+ return nil+ }+ if s.busyGate != nil && s.busyGate.RewindHeld(sessionID) {+ return sandbox.ErrSessionRewindLocked}+ type rewindLockReader interface {+ HasRewindLock(context.Context, string) (bool, error)+ }+ check := func(mgr sandbox.Manager) error {+ if mgr == nil {+ return nil+ }+ reader, ok := mgr.(rewindLockReader)+ if !ok {+ return nil+ }+ held, err := reader.HasRewindLock(ctx, sessionID)+ if err != nil {+ return err+ }+ if held {+ return sandbox.ErrSessionRewindLocked+ }+ return nil+ }+ return check(s.sandboxMgr)+}++// HoldSandboxTurn is the exported turn-lease entry so HTTP send can take the+// lease before persisting messages, matching rewind's busy check.+func (s *sessionService) HoldSandboxTurn(+ ctx context.Context, sessionID, configID string,+) (func(), error) {+ return s.holdSandboxTurn(ctx, sessionID, configID)}diff --git a/internal/application/service/session_agent_qa.go b/internal/application/service/session_agent_qa.goindex fc55be56b..f5e69590a 100644--- a/internal/application/service/session_agent_qa.go+++ b/internal/application/service/session_agent_qa.go@@ -169,9 +169,15 @@ func (s *sessionService) AgentQA(// Hold the sandbox across this turn so an install that finishes while we// are running cannot rebuild the VM between tool calls. Staging below is// the first resolve: if the previous turn left a stale mark, that is- // where the new image is picked up.- releaseTurn := s.holdSandboxTurn(ctx, sessionID, agentConfig.SandboxConfigID)- defer releaseTurn()+ // where the new image is picked up. HTTP send already holds the lease it+ // took before persisting the turn, so only direct callers take one here.+ if !req.TurnLeaseHeld {+ releaseTurn, err := s.holdSandboxTurn(ctx, sessionID, agentConfig.SandboxConfigID)+ if err != nil {+ return err+ }+ defer releaseTurn()+ }// Reconcile all durable session attachments into the session's remote// sandbox before the model can request shell or skill execution. Thediff --git a/internal/application/service/session_busy_gate.go b/internal/application/service/session_busy_gate.gonew file mode 100644index 000000000..4ca6ec55e--- /dev/null+++ b/internal/application/service/session_busy_gate.go@@ -0,0 +1,121 @@+package service++import (+ "strings"+ "sync"++ "github.com/Tencent/WeKnora/internal/sandbox"+)++// SessionBusyGate is process-local exclusion between send and rewind when+// there is no sandbox manager (and a second line when there is). Redis turn+// leases do not cover a process without that manager; this map does.+type SessionBusyGate struct {+ mu sync.Mutex+ states map[string]*sessionBusyState+}++type sessionBusyState struct {+ sendRefs int+ rewind bool+}++// NewSessionBusyGate returns an empty gate. Container provides one shared+// instance so send and rewind see each other in-process.+func NewSessionBusyGate() *SessionBusyGate {+ return &SessionBusyGate{states: make(map[string]*sessionBusyState)}+}++func (g *SessionBusyGate) stateLocked(sessionID string) *sessionBusyState {+ st := g.states[sessionID]+ if st == nil {+ st = &sessionBusyState{}+ g.states[sessionID] = st+ }+ return st+}++func (g *SessionBusyGate) dropLocked(sessionID string, st *sessionBusyState) {+ if st.sendRefs <= 0 && !st.rewind {+ delete(g.states, sessionID)+ }+}++// HoldSend marks sessionID as generating. Fails when rewind already holds it.+func (g *SessionBusyGate) HoldSend(sessionID string) (func(), error) {+ noop := func() {}+ if g == nil {+ return noop, nil+ }+ sessionID = strings.TrimSpace(sessionID)+ if sessionID == "" {+ return noop, nil+ }+ g.mu.Lock()+ defer g.mu.Unlock()+ st := g.stateLocked(sessionID)+ if st.rewind {+ return noop, sandbox.ErrSessionRewindLocked+ }+ st.sendRefs+++ var once sync.Once+ return func() {+ once.Do(func() {+ g.mu.Lock()+ defer g.mu.Unlock()+ st := g.states[sessionID]+ if st == nil {+ return+ }+ st.sendRefs--+ if st.sendRefs < 0 {+ st.sendRefs = 0+ }+ g.dropLocked(sessionID, st)+ })+ }, nil+}++// TryLockRewind takes exclusive rewind ownership. Fails when a send hold+// or another rewind already owns the session.+func (g *SessionBusyGate) TryLockRewind(sessionID string) (func(), error) {+ noop := func() {}+ if g == nil {+ return noop, nil+ }+ sessionID = strings.TrimSpace(sessionID)+ if sessionID == "" {+ return noop, nil+ }+ g.mu.Lock()+ defer g.mu.Unlock()+ st := g.stateLocked(sessionID)+ if st.rewind || st.sendRefs > 0 {+ return noop, ErrRewindSourceBusy+ }+ st.rewind = true+ var once sync.Once+ return func() {+ once.Do(func() {+ g.mu.Lock()+ defer g.mu.Unlock()+ st := g.states[sessionID]+ if st == nil {+ return+ }+ st.rewind = false+ g.dropLocked(sessionID, st)+ })+ }, nil+}++// RewindHeld reports whether rewind currently owns sessionID.+func (g *SessionBusyGate) RewindHeld(sessionID string) bool {+ if g == nil {+ return false+ }+ g.mu.Lock()+ defer g.mu.Unlock()+ st := g.states[strings.TrimSpace(sessionID)]+ return st != nil && st.rewind+}diff --git a/internal/application/service/session_busy_gate_test.go b/internal/application/service/session_busy_gate_test.gonew file mode 100644index 000000000..b6fe3806f--- /dev/null+++ b/internal/application/service/session_busy_gate_test.go@@ -0,0 +1,60 @@+package service++import (+ "testing"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/stretchr/testify/require"+)++func TestSessionBusyGateSendBlocksRewind(t *testing.T) {+ gate := NewSessionBusyGate()++ release, err := gate.HoldSend("sess-1")+ require.NoError(t, err)++ _, err = gate.TryLockRewind("sess-1")+ require.ErrorIs(t, err, ErrRewindSourceBusy)++ release()+ unlock, err := gate.TryLockRewind("sess-1")+ require.NoError(t, err)+ unlock()+}++func TestSessionBusyGateRewindBlocksSend(t *testing.T) {+ gate := NewSessionBusyGate()++ unlock, err := gate.TryLockRewind("sess-1")+ require.NoError(t, err)+ require.True(t, gate.RewindHeld("sess-1"))++ _, err = gate.HoldSend("sess-1")+ require.ErrorIs(t, err, sandbox.ErrSessionRewindLocked)++ unlock()+ require.False(t, gate.RewindHeld("sess-1"))+ release, err := gate.HoldSend("sess-1")+ require.NoError(t, err)+ release()+}++func TestSessionBusyGateNestedSendHolds(t *testing.T) {+ gate := NewSessionBusyGate()+ first, err := gate.HoldSend("sess-1")+ require.NoError(t, err)+ second, err := gate.HoldSend("sess-1")+ require.NoError(t, err)++ _, err = gate.TryLockRewind("sess-1")+ require.ErrorIs(t, err, ErrRewindSourceBusy)++ first()+ _, err = gate.TryLockRewind("sess-1")+ require.ErrorIs(t, err, ErrRewindSourceBusy)++ second()+ unlock, err := gate.TryLockRewind("sess-1")+ require.NoError(t, err)+ unlock()+}diff --git a/internal/application/service/session_fork.go b/internal/application/service/session_fork.goindex 92303f485..22718b5b2 100644--- a/internal/application/service/session_fork.go+++ b/internal/application/service/session_fork.go@@ -440,6 +440,23 @@ func latestCheckpoint(history []*types.Message) *types.SandboxCheckpoint {return nil}+// latestReachableCheckpoint walks kept assistant messages until it finds one+// with a non-empty commit SHA. Rewind uses this so a failed last-turn+// checkpoint does not skip an earlier SHA that can still reset the workspace.+func latestReachableCheckpoint(history []*types.Message) *types.SandboxCheckpoint {+ for i := len(history) - 1; i >= 0; i-- {+ if history[i] == nil || history[i].Role != "assistant" {+ continue+ }+ cp := history[i].SandboxCheckpoint+ if cp == nil || strings.TrimSpace(cp.CommitSHA) == "" {+ continue+ }+ return cp+ }+ return nil+}+func hasAssistantMessage(history []*types.Message) bool {for _, m := range history {if m.Role == "assistant" {diff --git a/internal/application/service/session_fork_test.go b/internal/application/service/session_fork_test.goindex ad5cc6c9a..fab799e61 100644--- a/internal/application/service/session_fork_test.go+++ b/internal/application/service/session_fork_test.go@@ -76,6 +76,7 @@ type fakeSessionStore struct {updatedBootstrap *types.ForkBootstrapbootstrapCleared boolclearErr error+ updateErr errorunconsumed []*types.SessioncreateErr errorleases []*types.ForkSnapshotLease@@ -107,6 +108,9 @@ func (f *fakeSessionStore) UpdateForkBootstrap(_ context.Context, _ string, b *t}return nil}+ if f.updateErr != nil {+ return f.updateErr+ }copied := *bf.updatedBootstrap = &copiedif f.source != nil {@@ -215,9 +219,15 @@ func (f *fakeSessionStore) copiedFromIDs() []string {// fakeMessageStore is the narrow message port SessionForkService needs.type fakeMessageStore struct {- messages []*types.Message- lastListedIDs []string- rewriteErr error+ messages []*types.Message+ lastListedIDs []string+ rewriteErr error+ deleteFromCalls int+ lastDeleteInclusive *bool+ deleteFromErr error+ deleteFromFailTimes int+ tombstoned []types.ArtifactRef+ liveArtifacts []types.MessageArtifactRecord}func newFakeMessageStore(messages []*types.Message) *fakeMessageStore {@@ -308,6 +318,113 @@ func (f *fakeMessageStore) GetSessionArtifacts(ctx context.Context, sessionID streturn out, nil}+func (f *fakeMessageStore) DeleteMessagesFrom(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string, inclusive bool,+) ([]*types.Message, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ f.deleteFromCalls+++ inc := inclusive+ f.lastDeleteInclusive = &inc+ if f.deleteFromErr != nil {+ return nil, f.deleteFromErr+ }+ if f.deleteFromFailTimes > 0 {+ f.deleteFromFailTimes--+ return nil, errors.New("delete messages: temporary failure")+ }+ var deleted, kept []*types.Message+ for _, m := range f.messages {+ if m == nil {+ continue+ }+ if m.SessionID != sessionID {+ kept = append(kept, m)+ continue+ }+ after := m.CreatedAt.After(boundary) || (m.CreatedAt.Equal(boundary) && m.ID > boundaryID)+ atBoundary := m.CreatedAt.Equal(boundary) && m.ID == boundaryID+ if after || (inclusive && atBoundary) {+ deleted = append(deleted, m)+ for i, art := range m.Artifacts {+ if art.DeletedAt != nil {+ continue+ }+ f.liveArtifacts = append(f.liveArtifacts, types.MessageArtifactRecord{+ SessionID: sessionID,+ MessageID: m.ID,+ Position: i,+ URL: art.URL,+ FileName: art.FileName,+ })+ }+ continue+ }+ kept = append(kept, m)+ }+ sort.Slice(deleted, func(i, j int) bool {+ if !deleted[i].CreatedAt.Equal(deleted[j].CreatedAt) {+ return deleted[i].CreatedAt.Before(deleted[j].CreatedAt)+ }+ return deleted[i].ID < deleted[j].ID+ })+ f.messages = kept+ return deleted, nil+}++func (f *fakeMessageStore) GetRecentMessagesBySession(+ ctx context.Context, sessionID string, limit int,+) ([]*types.Message, error) {+ all, err := f.GetMessagesBySession(ctx, sessionID, 1, 0)+ if err != nil {+ return nil, err+ }+ if limit <= 0 || len(all) <= limit {+ return all, nil+ }+ return all[len(all)-limit:], nil+}++func (f *fakeMessageStore) SessionHasIncompleteAssistant(+ _ context.Context, sessionID string,+) (bool, error) {+ for _, m := range f.messages {+ if m != nil && m.SessionID == sessionID && m.Role == "assistant" && !m.IsCompleted {+ return true, nil+ }+ }+ return false, nil+}++func (f *fakeMessageStore) ListLiveArtifactsByMessageIDs(+ _ context.Context, sessionID string, messageIDs []string,+) ([]types.MessageArtifactRecord, error) {+ want := make(map[string]struct{}, len(messageIDs))+ for _, id := range messageIDs {+ if id != "" {+ want[id] = struct{}{}+ }+ }+ var out []types.MessageArtifactRecord+ for _, row := range f.liveArtifacts {+ if row.SessionID != sessionID {+ continue+ }+ if _, ok := want[row.MessageID]; ok {+ out = append(out, row)+ }+ }+ return out, nil+}++func (f *fakeMessageStore) SoftDeleteSessionArtifacts(+ _ context.Context, _ string, refs []types.ArtifactRef, _ time.Time,+) ([]types.ArtifactRef, error) {+ f.tombstoned = append(f.tombstoned, refs...)+ return refs, nil+}+func (f *fakeMessageStore) RewriteSandboxCheckpoints(_ context.Context, sessionID, oldID, newID string) error {if f.rewriteErr != nil {return f.rewriteErr@@ -335,6 +452,8 @@ var (_ reaperSessionStore = (*fakeSessionStore)(nil)_ forkMessageStore = (*fakeMessageStore)(nil)_ forkBootstrapMessageStore = (*fakeMessageStore)(nil)+ _ rewindSessionStore = (*fakeSessionStore)(nil)+ _ rewindMessageStore = (*fakeMessageStore)(nil)_ SessionForkSandboxPort = (*fakeForkSandboxPort)(nil))diff --git a/internal/application/service/session_knowledge_qa.go b/internal/application/service/session_knowledge_qa.goindex 1b886157d..09a1e9190 100644--- a/internal/application/service/session_knowledge_qa.go+++ b/internal/application/service/session_knowledge_qa.go@@ -33,6 +33,24 @@ func (s *sessionService) KnowledgeQA(req.Query,webSearchEnabled,)+ // IM/MCP call KnowledgeQA without executeQA's send-side lease, so hold one+ // for the pipeline. HTTP send already took it before persisting the turn+ // and says so on the request; taking a second would double every rewind+ // check and lease round trip on the hot send path.+ if !req.TurnLeaseHeld {+ if err := s.RejectSendIfRewinding(ctx, req.Session.ID); err != nil {+ return err+ }+ configID := ""+ if req.CustomAgent != nil {+ configID = req.CustomAgent.Config.SandboxConfigID+ }+ releaseTurn, holdErr := s.holdSandboxTurn(ctx, req.Session.ID, configID)+ if holdErr != nil {+ return holdErr+ }+ defer releaseTurn()+ }// Span the request setup (KB / model resolution, search target building,// agent override application). This covers the visible gap between tracediff --git a/internal/application/service/session_rewind.go b/internal/application/service/session_rewind.gonew file mode 100644index 000000000..a9994d316--- /dev/null+++ b/internal/application/service/session_rewind.go@@ -0,0 +1,642 @@+// Package service - in-place session rewind.+//+// Rewind truncates the current session at a chosen user or assistant message+// and, when the live sandbox still holds that turn's git checkpoint, rolls+// /workspace back to it. Unlike fork it does not snapshot, does not create a+// session, and refuses the whole operation if git reset fails — a half-applied+// rewind (conversation gone, files still ahead) is harder to recover from+// than a 500 the user can retry.+//+// Unopened forks are the exception to "no sandbox means conversation only":+// they still carry ForkBootstrap for the first provision. Rewind retargets+// that SHA to the kept history, or drops the bootstrap when nothing remains+// to reset to, so the lazy sandbox cannot boot ahead of the transcript.+package service++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "time"++ apperrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "gorm.io/gorm"+)++// RewindSkipReason explains why rewind left the workspace alone. The+// conversation is still truncated; the code is so the client can say so.+// These are not shared with ForkDegradeReason: the two operations skip for+// overlapping-but-not-identical reasons and the UI copy is different.+type RewindSkipReason string++const (+ // RewindSkipNoSandbox means the session has no bound sandbox to reset.+ RewindSkipNoSandbox RewindSkipReason = "NO_SANDBOX"++ // RewindSkipNoCheckpoint means the history being kept has no git+ // checkpoint (the image has no git, or every kept turn failed to commit).+ RewindSkipNoCheckpoint RewindSkipReason = "NO_CHECKPOINT"+)++var (+ // ErrRewindSourceBusy reports that the session has an agent turn in+ // flight, or the rewind point is an unfinished assistant message. HTTP 409.+ ErrRewindSourceBusy = errors.New("session rewind: session has an active turn")++ // ErrRewindSessionNotFound covers a missing session and a session the+ // caller does not own. Both map to HTTP 404 so ownership is not enumerable.+ ErrRewindSessionNotFound = errors.New("session rewind: session not found")++ // ErrRewindMessageNotFound covers a missing message and a message that+ // belongs to a different session. HTTP 404.+ ErrRewindMessageNotFound = errors.New("session rewind: rewind point message not found")++ // ErrRewindMessageRole is returned when the rewind point exists but is+ // neither a user nor an assistant message. HTTP 400.+ ErrRewindMessageRole = errors.New("session rewind: rewind point must be a user or assistant message")++ // ErrRewindNoCheckpoint is returned when the session has a live sandbox+ // and kept history includes an assistant turn, but no reachable git SHA.+ // Truncating would leave files ahead of the conversation. HTTP 409.+ ErrRewindNoCheckpoint = errors.New("session rewind: no reachable workspace checkpoint")++ // ErrRewindSandboxReplaced is returned when the kept checkpoint belongs+ // to a sandbox the session no longer uses. Truncating would leave the+ // live workspace ahead of the conversation. HTTP 409.+ ErrRewindSandboxReplaced = errors.New("session rewind: sandbox was replaced")+)++const (+ rewindIncompleteLookback = 512+ rewindDeleteAttempts = 3+ rewindDeleteRetryWait = 50 * time.Millisecond+)++func isRewindNotFound(err error) bool {+ return errors.Is(err, apperrors.ErrSessionNotFound) || errors.Is(err, gorm.ErrRecordNotFound)+}++// RewindResult is what the HTTP layer renders.+// WorkspaceReset is true when the live sandbox was git-reset, or when an+// unopened fork's ForkBootstrap was retargeted so the first provision lands+// on the rewind SHA.+type RewindResult struct {+ DeletedMessages int `json:"deleted_messages"`+ WorkspaceReset bool `json:"workspace_reset"`+ Reason RewindSkipReason `json:"reason"`+}++// SessionRewindSandboxPort is the narrow sandbox surface rewind needs.+type SessionRewindSandboxPort interface {+ BoundSandboxID(ctx context.Context, sessionID string) (string, bool)+ HasActiveTurn(ctx context.Context, sessionID string) (bool, error)+ TryLockRewind(ctx context.Context, sessionID string) (unlock func(), err error)+ SandboxShellRunner+}++type rewindSessionStore interface {+ GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)+ UpdateForkBootstrap(ctx context.Context, sessionID string, b *types.ForkBootstrap) error+ forkSnapshotReleaseStore+}++type rewindMessageStore interface {+ GetMessage(ctx context.Context, sessionID, messageID string) (*types.Message, error)+ GetRecentMessagesBySession(ctx context.Context, sessionID string, limit int) ([]*types.Message, error)+ ListMessagesBySessionUpTo(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string,+ ) ([]*types.Message, error)+ DeleteMessagesFrom(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string, inclusive bool,+ ) ([]*types.Message, error)+}++type rewindIncompleteFinder interface {+ SessionHasIncompleteAssistant(ctx context.Context, sessionID string) (bool, error)+}++// rewindCheckpointLister is the cheap path for "which checkpoint does kept+// history still reach". Rewind never reads message bodies, so a store that+// can return the assistant turns alone — no content, no artifact join —+// answers it without dragging the whole conversation into memory.+type rewindCheckpointLister interface {+ ListAssistantCheckpointsUpTo(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string,+ ) ([]*types.Message, error)+}++type rewindArtifactJanitor interface {+ ListLiveArtifactsByMessageIDs(+ ctx context.Context, sessionID string, messageIDs []string,+ ) ([]types.MessageArtifactRecord, error)+ SoftDeleteSessionArtifacts(+ ctx context.Context, sessionID string, refs []types.ArtifactRef, at time.Time,+ ) ([]types.ArtifactRef, error)+}++type rewindLiveRunReader interface {+ GetLiveRun(ctx context.Context, sessionID string) (assistantMessageID, requestID string, err error)+}++type rewindStreamDropper interface {+ DropMessageStreams(ctx context.Context, sessionID string, messageIDs []string) error+}++type rewindKnowledgeCleaner interface {+ DeleteMessageKnowledge(ctx context.Context, knowledgeID string)+}++type rewindSuggestionCleaner interface {+ DeleteByMessageID(ctx context.Context, tenantID uint64, sessionID, messageID string) error+}++// rewindSuggestionBatchCleaner is the one-statement form of the above.+type rewindSuggestionBatchCleaner interface {+ DeleteByMessageIDs(ctx context.Context, tenantID uint64, sessionID string, messageIDs []string) error+}++// SessionRewindService implements in-place rewind.+type SessionRewindService struct {+ sessions rewindSessionStore+ messages rewindMessageStore+ sandbox SessionRewindSandboxPort+ knowledge rewindKnowledgeCleaner+ suggestions rewindSuggestionCleaner+ snapshots ForkSnapshotDeleter+ liveRuns rewindLiveRunReader+ busyGate *SessionBusyGate+}++// NewSessionRewindService wires the service. A nil sandbox port skips the+// workspace reset with NO_SANDBOX, which is the correct behaviour for a+// deployment without sandboxes.+func NewSessionRewindService(+ sessions rewindSessionStore,+ messages rewindMessageStore,+ sandboxPort SessionRewindSandboxPort,+ knowledge rewindKnowledgeCleaner,+ suggestions rewindSuggestionCleaner,+) *SessionRewindService {+ return &SessionRewindService{+ sessions: sessions,+ messages: messages,+ sandbox: sandboxPort,+ knowledge: knowledge,+ suggestions: suggestions,+ busyGate: NewSessionBusyGate(),+ }+}++// NewSessionRewindServiceFromRepos is the DI-friendly constructor.+func NewSessionRewindServiceFromRepos(+ sessions interfaces.SessionRepository,+ messages interfaces.MessageRepository,+ sandboxPort SessionRewindSandboxPort,+ knowledge interfaces.MessageService,+ suggestions interfaces.MessageSuggestionRepository,+ resolver sandbox.TenantSandboxResolver,+ fallback sandbox.Manager,+ streams interfaces.StreamManager,+ busyGate *SessionBusyGate,+) *SessionRewindService {+ s := NewSessionRewindService(sessions, messages, sandboxPort, knowledge, suggestions)+ s.snapshots = NewResolverForkSnapshotDeleter(resolver, fallback)+ s.liveRuns = streams+ if busyGate != nil {+ s.busyGate = busyGate+ }+ return s+}++// Rewind truncates sessionID at messageID and resets the live workspace when+// a reachable checkpoint exists.+//+// Errors are reserved for conditions the user must act on: a bad request, a+// session they do not own, a busy source, or a git reset that failed. Missing+// sandbox state degrades to a conversation-only rewind and is reported+// through RewindResult.Reason.+func (s *SessionRewindService) Rewind(+ ctx context.Context,+ tenantID uint64,+ userID string,+ sessionID string,+ messageID string,+) (*RewindResult, error) {+ source, err := s.sessions.GetByID(ctx, tenantID, sessionID)+ if err != nil {+ if isRewindNotFound(err) {+ return nil, ErrRewindSessionNotFound+ }+ return nil, fmt.Errorf("session rewind: load session: %w", err)+ }+ if source == nil {+ return nil, ErrRewindSessionNotFound+ }+ // Rewind is a write. Empty user_id rows are tenant-level channel/legacy+ // sessions: list/read scope still surfaces them, but mutating history+ // requires an exact owner match.+ if userID == "" || source.UserID != userID {+ return nil, ErrRewindSessionNotFound+ }++ rewindPoint, err := s.messages.GetMessage(ctx, sessionID, messageID)+ if err != nil {+ if isRewindNotFound(err) {+ return nil, ErrRewindMessageNotFound+ }+ return nil, fmt.Errorf("session rewind: load rewind point: %w", err)+ }+ if rewindPoint == nil {+ return nil, ErrRewindMessageNotFound+ }+ if rewindPoint.Role != "user" && rewindPoint.Role != "assistant" {+ return nil, ErrRewindMessageRole+ }+ if rewindPoint.Role == "assistant" && !rewindPoint.IsCompleted {+ return nil, ErrRewindSourceBusy+ }++ if err := s.rejectIfBusy(ctx, sessionID); err != nil {+ return nil, err+ }++ history, err := s.keptCheckpointHistory(ctx, sessionID, rewindPoint)+ if err != nil {+ return nil, err+ }++ // Client abort must not leave git reset applied and messages intact.+ // Once we are past the cheap busy reject, finish reset+truncate even if+ // the HTTP request is gone.+ persistCtx := context.WithoutCancel(ctx)+ unlock, err := s.lockRewind(persistCtx, sessionID)+ if err != nil {+ return nil, err+ }+ defer unlock()++ var abandonedBootstrap *types.ForkBootstrap+ workspaceReset, reason, resetErr := s.resetWorkspaceIfPossible(persistCtx, sessionID, history)+ if resetErr != nil {+ return nil, resetErr+ }+ if !workspaceReset {+ if err := s.rejectIfBusy(persistCtx, sessionID); err != nil {+ return nil, err+ }+ if reason == RewindSkipNoSandbox {+ aligned, abandoned, err := s.syncPendingForkBootstrap(persistCtx, source, history)+ if err != nil {+ return nil, err+ }+ if aligned {+ workspaceReset = true+ reason = ""+ } else if abandoned != nil {+ reason = RewindSkipNoCheckpoint+ abandonedBootstrap = abandoned+ }+ }+ }++ inclusive := rewindPoint.Role == "user"+ deleted, err := s.deleteMessagesFrom(+ persistCtx, sessionID, rewindPoint.CreatedAt, rewindPoint.ID, inclusive,+ )+ if err != nil {+ if workspaceReset {+ return nil, fmt.Errorf("session rewind: delete messages after workspace reset: %w", err)+ }+ return nil, fmt.Errorf("session rewind: delete messages: %w", err)+ }++ // Deleting the snapshot is the one step of the bootstrap handover that+ // cannot be undone, so it waits until the truncate has actually landed.+ // Everything above it is a DB write the next rewind attempt can redo.+ s.releaseAbandonedForkSnapshot(persistCtx, source, abandonedBootstrap)++ s.cleanupDeleted(persistCtx, source.TenantID, sessionID, deleted)++ logger.Infof(ctx,+ "[SessionRewind] session=%s rewind_point=%s deleted=%d workspace_reset=%v reason=%s",+ sessionID, rewindPoint.ID, len(deleted), workspaceReset, reason)++ return &RewindResult{+ DeletedMessages: len(deleted),+ WorkspaceReset: workspaceReset,+ Reason: reason,+ }, nil+}++// keptCheckpointHistory returns the messages that survive the cut, in the+// shape latestReachableCheckpoint and hasAssistantMessage read them.+//+// Only assistant turns carry a SandboxCheckpoint and only assistant turns+// decide between "reset to a SHA", "empty-reset" and ErrRewindNoCheckpoint,+// so a store that can list just those is asked for just those. The fallback+// reads the full prefix, which is correct but loads every message body and+// artifact row in the session to answer a question about a handful of rows.+func (s *SessionRewindService) keptCheckpointHistory(+ ctx context.Context, sessionID string, rewindPoint *types.Message,+) ([]*types.Message, error) {+ var (+ kept []*types.Message+ err error+ )+ if lister, ok := s.messages.(rewindCheckpointLister); ok {+ kept, err = lister.ListAssistantCheckpointsUpTo(+ ctx, sessionID, rewindPoint.CreatedAt, rewindPoint.ID,+ )+ } else {+ kept, err = s.messages.ListMessagesBySessionUpTo(+ ctx, sessionID, rewindPoint.CreatedAt, rewindPoint.ID,+ )+ }+ if err != nil {+ return nil, fmt.Errorf("session rewind: load history: %w", err)+ }+ return historyThroughForkPoint(kept, rewindPoint), nil+}++func (s *SessionRewindService) resetWorkspaceIfPossible(+ ctx context.Context, sessionID string, history []*types.Message,+) (bool, RewindSkipReason, error) {+ if s.sandbox == nil {+ return false, RewindSkipNoSandbox, nil+ }+ currentID, ok := s.sandbox.BoundSandboxID(ctx, sessionID)+ if !ok || strings.TrimSpace(currentID) == "" {+ return false, RewindSkipNoSandbox, nil+ }+ checkpoint := latestReachableCheckpoint(history)+ if checkpoint == nil {+ if hasAssistantMessage(history) {+ return false, "", ErrRewindNoCheckpoint+ }+ if err := s.rejectIfBusy(ctx, sessionID); err != nil {+ return false, "", err+ }+ workCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), workspaceResetTimeout)+ defer cancel()+ if err := resetWorkspaceToEmpty(workCtx, s.sandbox, sessionID, currentID); err != nil {+ return false, "", fmt.Errorf("session rewind: reset workspace: %w", err)+ }+ return true, "", nil+ }+ if currentID != checkpoint.SandboxID {+ return false, "", ErrRewindSandboxReplaced+ }++ // Re-check immediately before git reset --hard. The entry check is a+ // cheap reject; a turn can start while we look up the checkpoint.+ if err := s.rejectIfBusy(ctx, sessionID); err != nil {+ return false, "", err+ }++ workCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), workspaceResetTimeout)+ defer cancel()+ if err := resetWorkspaceToCommit(+ workCtx, s.sandbox, sessionID, checkpoint.CommitSHA, checkpoint.SandboxID,+ ); err != nil {+ return false, "", fmt.Errorf("session rewind: reset workspace: %w", err)+ }+ return true, "", nil+}++func (s *SessionRewindService) deleteMessagesFrom(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string, inclusive bool,+) ([]*types.Message, error) {+ if s == nil || s.messages == nil {+ return nil, nil+ }+ var lastErr error+ for attempt := 1; attempt <= rewindDeleteAttempts; attempt++ {+ deleted, err := s.messages.DeleteMessagesFrom(+ ctx, sessionID, boundary, boundaryID, inclusive,+ )+ if err == nil {+ return deleted, nil+ }+ lastErr = err+ if attempt == rewindDeleteAttempts {+ break+ }+ timer := time.NewTimer(rewindDeleteRetryWait)+ select {+ case <-ctx.Done():+ if !timer.Stop() {+ <-timer.C+ }+ return nil, err+ case <-timer.C:+ }+ }+ return nil, lastErr+}++func (s *SessionRewindService) lockRewind(ctx context.Context, sessionID string) (func(), error) {+ unlockGate, err := s.busyGate.TryLockRewind(sessionID)+ if err != nil {+ return nil, ErrRewindSourceBusy+ }+ unlockPort := func() {}+ if s.sandbox != nil {+ unlock, err := s.sandbox.TryLockRewind(ctx, sessionID)+ if err != nil {+ unlockGate()+ if errors.Is(err, sandbox.ErrSessionRewindLocked) ||+ errors.Is(err, sandbox.ErrSessionTurnActive) ||+ errors.Is(err, ErrRewindSourceBusy) {+ return nil, ErrRewindSourceBusy+ }+ return nil, fmt.Errorf("session rewind: lock session: %w", err)+ }+ if unlock != nil {+ unlockPort = unlock+ }+ }+ return func() {+ unlockPort()+ unlockGate()+ }, nil+}++func (s *SessionRewindService) rejectIfBusy(ctx context.Context, sessionID string) error {+ if s.liveRuns != nil {+ liveID, _, err := s.liveRuns.GetLiveRun(ctx, sessionID)+ if err != nil {+ return fmt.Errorf("session rewind: check live run: %w", err)+ }+ if strings.TrimSpace(liveID) != "" {+ return ErrRewindSourceBusy+ }+ }+ if err := s.rejectIfIncompleteTurn(ctx, sessionID); err != nil {+ return err+ }+ if s.sandbox == nil {+ return nil+ }+ busy, turnErr := s.sandbox.HasActiveTurn(ctx, sessionID)+ if turnErr != nil {+ return fmt.Errorf("session rewind: check turn state: %w", turnErr)+ }+ if busy {+ return ErrRewindSourceBusy+ }+ return nil+}++func (s *SessionRewindService) rejectIfIncompleteTurn(ctx context.Context, sessionID string) error {+ if s.messages == nil {+ return nil+ }+ if finder, ok := s.messages.(rewindIncompleteFinder); ok {+ busy, err := finder.SessionHasIncompleteAssistant(ctx, sessionID)+ if err != nil {+ return fmt.Errorf("session rewind: check incomplete turn: %w", err)+ }+ if busy {+ return ErrRewindSourceBusy+ }+ return nil+ }+ msgs, err := s.messages.GetRecentMessagesBySession(ctx, sessionID, rewindIncompleteLookback)+ if err != nil {+ return fmt.Errorf("session rewind: check incomplete turn: %w", err)+ }+ for _, msg := range msgs {+ if msg != nil && msg.Role == "assistant" && !msg.IsCompleted {+ return ErrRewindSourceBusy+ }+ }+ return nil+}++// syncPendingForkBootstrap keeps an unopened fork's lazy sandbox in line with+// the conversation just truncated. ForkBootstrap.CommitSHA is applied the+// first time the session provisions a sandbox; leaving the fork-point SHA+// after an earlier rewind would boot the workspace ahead of the remaining+// messages. No remaining checkpoint means the next sandbox should be ordinary,+// same as forking at the first user message.+//+// A non-nil abandoned return is the bootstrap that was just cleared; its+// snapshot is still alive and the caller releases it once the truncate has+// landed. Clearing the column here and freeing the snapshot later keeps the+// whole handover redoable while the conversation can still fail to delete.+func (s *SessionRewindService) syncPendingForkBootstrap(+ ctx context.Context, session *types.Session, kept []*types.Message,+) (aligned bool, abandoned *types.ForkBootstrap, err error) {+ if s == nil || session == nil || session.ForkBootstrap == nil || session.ForkBootstrap.Consumed() {+ return false, nil, nil+ }+ pending := *session.ForkBootstrap+ checkpoint := latestReachableCheckpoint(kept)+ if checkpoint == nil || strings.TrimSpace(checkpoint.CommitSHA) == "" {+ if err := s.sessions.UpdateForkBootstrap(ctx, session.ID, nil); err != nil {+ return false, nil, fmt.Errorf("session rewind: clear fork bootstrap: %w", err)+ }+ return false, &pending, nil+ }+ sha := strings.TrimSpace(checkpoint.CommitSHA)+ if !gitSHAPattern.MatchString(sha) {+ return false, nil, fmt.Errorf("session rewind: invalid checkpoint sha %q", truncateForLog(sha))+ }+ if sha == strings.TrimSpace(pending.CommitSHA) {+ return true, nil, nil+ }+ pending.CommitSHA = sha+ if err := s.sessions.UpdateForkBootstrap(ctx, session.ID, &pending); err != nil {+ return false, nil, fmt.Errorf("session rewind: retarget fork bootstrap: %w", err)+ }+ return true, nil, nil+}++// releaseAbandonedForkSnapshot frees the snapshot behind a bootstrap that+// syncPendingForkBootstrap cleared. It runs after the messages are gone+// because the delete is irreversible: dropping the snapshot first and then+// failing to truncate would leave the fork with no workspace to boot from+// while its whole transcript is still there.+func (s *SessionRewindService) releaseAbandonedForkSnapshot(+ ctx context.Context, session *types.Session, pending *types.ForkBootstrap,+) {+ if s == nil || session == nil || pending == nil {+ return+ }+ view := *session+ view.ForkBootstrap = pending+ releaseForkSnapshotOnDelete(ctx, s.sessions, s.snapshots, &view)+}++// deleteSuggestions drops the follow-up questions hanging off the deleted+// messages, in one statement when the store can batch. A long rewind deletes+// hundreds of messages and the rewind lock is held for all of it.+func (s *SessionRewindService) deleteSuggestions(+ ctx context.Context, tenantID uint64, sessionID string, ids []string,+) {+ if s.suggestions == nil {+ return+ }+ if batch, ok := s.suggestions.(rewindSuggestionBatchCleaner); ok {+ if err := batch.DeleteByMessageIDs(ctx, tenantID, sessionID, ids); err != nil {+ logger.Warnf(ctx, "[SessionRewind] delete suggestions for session %s: %v", sessionID, err)+ }+ return+ }+ for _, id := range ids {+ if err := s.suggestions.DeleteByMessageID(ctx, tenantID, sessionID, id); err != nil {+ logger.Warnf(ctx, "[SessionRewind] delete suggestions for message %s: %v", id, err)+ }+ }+}++func (s *SessionRewindService) cleanupDeleted(+ ctx context.Context, tenantID uint64, sessionID string, deleted []*types.Message,+) {+ ids := make([]string, 0, len(deleted))+ for _, msg := range deleted {+ if msg == nil || msg.ID == "" {+ continue+ }+ ids = append(ids, msg.ID)+ if s.knowledge != nil && strings.TrimSpace(msg.KnowledgeID) != "" {+ s.knowledge.DeleteMessageKnowledge(ctx, msg.KnowledgeID)+ }+ }+ if len(ids) == 0 {+ return+ }+ s.deleteSuggestions(ctx, tenantID, sessionID, ids)+ if dropper, ok := s.liveRuns.(rewindStreamDropper); ok {+ if err := dropper.DropMessageStreams(ctx, sessionID, ids); err != nil {+ logger.Warnf(ctx, "[SessionRewind] drop streams for session %s: %v", sessionID, err)+ }+ }+ janitor, ok := s.messages.(rewindArtifactJanitor)+ if !ok {+ return+ }+ records, err := janitor.ListLiveArtifactsByMessageIDs(ctx, sessionID, ids)+ if err != nil {+ logger.Warnf(ctx, "[SessionRewind] list artifacts for session %s: %v", sessionID, err)+ return+ }+ refs := make([]types.ArtifactRef, 0, len(records))+ for _, row := range records {+ if row.MessageID == "" || row.Position < 0 {+ continue+ }+ refs = append(refs, types.ArtifactRef{MessageID: row.MessageID, Position: row.Position})+ }+ if len(refs) == 0 {+ return+ }+ if _, err := janitor.SoftDeleteSessionArtifacts(ctx, sessionID, refs, time.Now()); err != nil {+ logger.Warnf(ctx, "[SessionRewind] tombstone artifacts for session %s: %v", sessionID, err)+ }+}diff --git a/internal/application/service/session_rewind_test.go b/internal/application/service/session_rewind_test.gonew file mode 100644index 000000000..1bf8f3583--- /dev/null+++ b/internal/application/service/session_rewind_test.go@@ -0,0 +1,894 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+)++const (+ rewindSHA1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+ rewindSHA2 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+)++type fakeRewindSandboxPort struct {+ boundID string+ bound bool+ activeTurn bool+ activeTurnErr error+ busyAfterCalls int+ hasActiveTurnCalls int+ runner *fakeShellRunner+ execBlock func()+ rewindMu sync.Mutex+ rewindHeld bool+}++func newFakeRewindPort() *fakeRewindSandboxPort {+ return &fakeRewindSandboxPort{+ boundID: "sbx-1",+ bound: true,+ runner: &fakeShellRunner{result: &sandbox.ExecuteResult{ExitCode: 0}},+ }+}++var _ SessionRewindSandboxPort = (*fakeRewindSandboxPort)(nil)++func (f *fakeRewindSandboxPort) BoundSandboxID(context.Context, string) (string, bool) {+ return f.boundID, f.bound+}++func (f *fakeRewindSandboxPort) HasActiveTurn(context.Context, string) (bool, error) {+ f.hasActiveTurnCalls+++ if f.activeTurnErr != nil {+ return false, f.activeTurnErr+ }+ if f.busyAfterCalls > 0 && f.hasActiveTurnCalls > f.busyAfterCalls {+ return true, nil+ }+ return f.activeTurn, nil+}++func (f *fakeRewindSandboxPort) TryLockRewind(context.Context, string) (func(), error) {+ f.rewindMu.Lock()+ defer f.rewindMu.Unlock()+ if f.rewindHeld {+ return nil, ErrRewindSourceBusy+ }+ f.rewindHeld = true+ return func() {+ f.rewindMu.Lock()+ f.rewindHeld = false+ f.rewindMu.Unlock()+ }, nil+}++func (f *fakeRewindSandboxPort) ExecShellCommand(+ ctx context.Context, sessionID, command, workDir string,+ timeout time.Duration, env map[string]string,+) (*sandbox.ExecuteResult, error) {+ if f.execBlock != nil {+ f.execBlock()+ }+ if f.runner == nil {+ return &sandbox.ExecuteResult{ExitCode: 0}, nil+ }+ return f.runner.ExecShellCommand(ctx, sessionID, command, workDir, timeout, env)+}++type fakeLiveRunReader struct {+ assistantID string+}++func (f *fakeLiveRunReader) GetLiveRun(context.Context, string) (string, string, error) {+ if f == nil {+ return "", "", nil+ }+ return f.assistantID, "req", nil+}++type fakeRewindStream struct {+ fakeLiveRunReader+ dropped []string+}++func (f *fakeRewindStream) DropMessageStreams(_ context.Context, _ string, messageIDs []string) error {+ f.dropped = append(f.dropped, messageIDs...)+ return nil+}++func rewindCompletedTurn(userID, assistantID, sandboxID, sha string, offset time.Duration) []*types.Message {+ turn := checkpointedTurn(userID, assistantID, sandboxID, sha, offset)+ turn[1].IsCompleted = true+ return turn+}++func newRewindFixture(t *testing.T, port SessionRewindSandboxPort, messages []*types.Message) (+ *SessionRewindService, *fakeMessageStore,+) {+ t.Helper()+ sessions := newFakeSessionStore(&types.Session{+ ID: "src", TenantID: 1, UserID: "u1", Title: "原会话", SandboxConfigID: "cfg-1",+ })+ msgs := newFakeMessageStore(messages)+ return NewSessionRewindService(sessions, msgs, port, nil, nil), msgs+}++func TestRewindUserPointDeletesItselfAndResetsToPreviousAssistant(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn1, later...))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.Equal(t, 2, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Empty(t, got.Reason)+ require.NotNil(t, msgs.lastDeleteInclusive)+ require.True(t, *msgs.lastDeleteInclusive)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+ require.Len(t, port.runner.calls, 1)+ require.Contains(t, port.runner.calls[0], rewindSHA1)+ require.NotContains(t, port.runner.calls[0], rewindSHA2)+}++func TestRewindAssistantPointKeepsItselfAndResetsToItsCheckpoint(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn1, later...))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "a-1")++ require.NoError(t, err)+ require.Equal(t, 2, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Empty(t, got.Reason)+ require.NotNil(t, msgs.lastDeleteInclusive)+ require.False(t, *msgs.lastDeleteInclusive)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+ require.Len(t, port.runner.calls, 1)+ require.Contains(t, port.runner.calls[0], rewindSHA1)+}++func TestRewindIncompleteAssistantPointIsBusy(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ turn[1].IsCompleted = false+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, turn)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "a-1")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindActiveTurnIsBusy(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.activeTurn = true+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindSystemRoleIsRejected(t *testing.T) {+ msg := &types.Message{+ ID: "sys-1", SessionID: "src", Role: "system", CreatedAt: forkBase,+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, []*types.Message{msg})++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "sys-1")++ require.ErrorIs(t, err, ErrRewindMessageRole)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+}++func TestRewindForeignUserIsNotFound(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, turn)++ got, err := svc.Rewind(context.Background(), 1, "other", "src", "u-1")++ require.ErrorIs(t, err, ErrRewindSessionNotFound)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+}++func TestRewindNoSandboxDeletesMessagesWithoutShell(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", Content: "retry",+ CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.bound = false+ port.boundID = ""+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.Equal(t, 1, got.DeletedMessages)+ require.False(t, got.WorkspaceReset)+ require.Equal(t, RewindSkipNoSandbox, got.Reason)+ require.Empty(t, port.runner.calls)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+}++func TestRewindNoCheckpointOnLiveSandboxDoesNotDeleteMessages(t *testing.T) {+ history := []*types.Message{+ {ID: "u-1", SessionID: "src", Role: "user", CreatedAt: forkBase},+ {+ ID: "a-1", SessionID: "src", Role: "assistant", IsCompleted: true,+ CreatedAt: forkBase.Add(time.Second),+ },+ {ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second)},+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, history)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.ErrorIs(t, err, ErrRewindNoCheckpoint)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+ require.Equal(t, []string{"u-1", "a-1", "u-2"}, messageIDs(msgs.messages))+}++func TestRewindReplacedSandboxDoesNotDeleteMessages(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-old", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.boundID = "sbx-new"+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.ErrorIs(t, err, ErrRewindSandboxReplaced)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1", "u-2"}, messageIDs(msgs.messages))+ require.Empty(t, port.runner.calls)+}++func TestRewindResetFailureDoesNotDeleteMessages(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.runner.err = errors.New("sandbox unreachable")+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.Error(t, err)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1", "u-2"}, messageIDs(msgs.messages))+ require.True(t, strings.Contains(err.Error(), "sandbox unreachable") ||+ strings.Contains(err.Error(), "workspace reset"))+}++func TestRewindCanceledRequestStillDeletesAfterReset(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ got, err := svc.Rewind(ctx, 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.NotNil(t, got)+ require.Equal(t, 1, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Len(t, port.runner.calls, 1)+ require.Equal(t, 1, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+}++func TestRewindTurnStartingBeforeResetIsBusy(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.busyAfterCalls = 1+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.GreaterOrEqual(t, port.hasActiveTurnCalls, 2)+ require.Empty(t, port.runner.calls)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1", "u-2"}, messageIDs(msgs.messages))+}++func TestRewindTurnStartingBeforeDeleteWhenSkippingWorkspaceIsBusy(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.bound = false+ port.boundID = ""+ port.busyAfterCalls = 1+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.GreaterOrEqual(t, port.hasActiveTurnCalls, 2)+ require.Empty(t, port.runner.calls)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1", "u-2"}, messageIDs(msgs.messages))+}++func TestRewindRejectsEmptyOwnerSession(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ port := newFakeRewindPort()+ sessions := newFakeSessionStore(&types.Session{+ ID: "src", TenantID: 1, UserID: "", Title: "租户会话",+ })+ msgs := newFakeMessageStore(turn)+ svc := NewSessionRewindService(sessions, msgs, port, nil, nil)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.ErrorIs(t, err, ErrRewindSessionNotFound)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindRejectsEmptyCaller(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, turn)++ got, err := svc.Rewind(context.Background(), 1, "", "src", "u-1")++ require.ErrorIs(t, err, ErrRewindSessionNotFound)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindMessageFromOtherSessionIsNotFound(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ foreign := &types.Message{+ ID: "foreign", SessionID: "other", Role: "user", CreatedAt: forkBase,+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn, foreign))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "foreign")++ require.ErrorIs(t, err, ErrRewindMessageNotFound)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindFirstUserMessageClearsConversationWithoutCheckpoint(t *testing.T) {+ history := []*types.Message{+ {ID: "u-1", SessionID: "src", Role: "user", Content: "hello", CreatedAt: forkBase},+ {+ ID: "a-1", SessionID: "src", Role: "assistant", IsCompleted: true,+ CreatedAt: forkBase.Add(time.Second),+ SandboxCheckpoint: &types.SandboxCheckpoint{+ SandboxID: "sbx-1", CommitSHA: rewindSHA1, CommittedAt: forkBase.Add(time.Second),+ },+ },+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, history)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.NoError(t, err)+ require.Equal(t, 2, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Empty(t, got.Reason)+ require.Len(t, port.runner.calls, 1)+ require.Contains(t, port.runner.calls[0], "commit-tree")+ require.Contains(t, port.runner.calls[0], "reset --hard")+ require.Contains(t, port.runner.calls[0], "clean -fdx")+ require.NotContains(t, port.runner.calls[0], `find "$WORK_TREE"`)+ require.Empty(t, msgs.messages)+}++func TestRewindWalksToEarlierCheckpointWhenLatestAssistantHasNone(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := []*types.Message{+ {ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second)},+ {+ ID: "a-2", SessionID: "src", Role: "assistant", IsCompleted: true,+ CreatedAt: forkBase.Add(11 * time.Second),+ },+ {ID: "u-3", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(20 * time.Second)},+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn1, later...))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-3")++ require.NoError(t, err)+ require.Equal(t, 1, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Len(t, port.runner.calls, 1)+ require.Contains(t, port.runner.calls[0], rewindSHA1)+ require.Equal(t, []string{"u-1", "a-1", "u-2", "a-2"}, messageIDs(msgs.messages))+}++func TestRewindLiveRunIsBusy(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))+ svc.liveRuns = &fakeLiveRunReader{assistantID: "a-live"}++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindIncompleteTurnPastOldestPageIsBusy(t *testing.T) {+ history := make([]*types.Message, 0, 1001)+ for i := 0; i < 1000; i++ {+ history = append(history, &types.Message{+ ID: fmt.Sprintf("old-%04d", i),+ SessionID: "src",+ Role: "user",+ CreatedAt: forkBase.Add(time.Duration(i) * time.Millisecond),+ })+ }+ history = append(history, &types.Message{+ ID: "late-a", SessionID: "src", Role: "assistant", IsCompleted: false,+ CreatedAt: forkBase.Add(time.Second),+ })+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, history)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "old-0000")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func TestRewindRetriesDeleteAfterWorkspaceReset(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))+ msgs.deleteFromFailTimes = 2++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.Equal(t, 1, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Equal(t, 3, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+}++func TestRewindCleansArtifactsAndStreamsForDeletedMessages(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ later[1].Artifacts = types.MessageArtifacts{{URL: "blob://a2", FileName: "out.txt"}}+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn, later...))+ streams := &fakeRewindStream{}+ svc.liveRuns = streams++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "a-1")++ require.NoError(t, err)+ require.Equal(t, 2, got.DeletedMessages)+ require.Equal(t, []types.ArtifactRef{{MessageID: "a-2", Position: 0}}, msgs.tombstoned)+ require.Equal(t, []string{"u-2", "a-2"}, streams.dropped)+}++func TestRewindIncompleteLaterTurnIsBusy(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := []*types.Message{+ {ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second)},+ {+ ID: "a-2", SessionID: "src", Role: "assistant", IsCompleted: false,+ CreatedAt: forkBase.Add(11 * time.Second),+ },+ }+ port := newFakeRewindPort()+ svc, msgs := newRewindFixture(t, port, append(turn, later...))++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Empty(t, port.runner.calls)+}++func pendingForkBootstrap(sha string) *types.ForkBootstrap {+ return &types.ForkBootstrap{+ SnapshotID: "snap-1",+ CommitSHA: sha,+ SourceSandboxID: "sbx-1",+ CreatedAt: forkBase,+ }+}++func newUnopenedForkRewindFixture(+ t *testing.T, messages []*types.Message, bootstrap *types.ForkBootstrap,+) (*SessionRewindService, *fakeSessionStore, *fakeMessageStore, *fakeRewindSandboxPort) {+ t.Helper()+ port := newFakeRewindPort()+ port.bound = false+ port.boundID = ""+ sessions := newFakeSessionStore(&types.Session{+ ID: "src", TenantID: 1, UserID: "u1", Title: "分支",+ SandboxConfigID: "cfg-1", ForkBootstrap: bootstrap,+ })+ msgs := newFakeMessageStore(messages)+ svc := NewSessionRewindService(sessions, msgs, port, nil, nil)+ return svc, sessions, msgs, port+}++func TestRewindUnopenedForkRetargetsBootstrapToKeptCheckpoint(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ svc, sessions, msgs, port := newUnopenedForkRewindFixture(+ t, append(turn1, later...), pendingForkBootstrap(rewindSHA2),+ )++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.Equal(t, 2, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Empty(t, got.Reason)+ require.Empty(t, port.runner.calls)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+ require.NotNil(t, sessions.source.ForkBootstrap)+ require.Equal(t, rewindSHA1, sessions.source.ForkBootstrap.CommitSHA)+ require.Equal(t, "snap-1", sessions.source.ForkBootstrap.SnapshotID)+ require.Equal(t, "sbx-1", sessions.source.ForkBootstrap.SourceSandboxID)+ require.False(t, sessions.source.ForkBootstrap.Consumed())+ require.False(t, sessions.bootstrapCleared)+}++func TestRewindUnopenedForkWalksToEarlierCheckpoint(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := []*types.Message{+ {ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second)},+ {+ ID: "a-2", SessionID: "src", Role: "assistant", IsCompleted: true,+ CreatedAt: forkBase.Add(11 * time.Second),+ },+ {ID: "u-3", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(20 * time.Second)},+ }+ svc, sessions, msgs, port := newUnopenedForkRewindFixture(+ t, append(turn1, later...), pendingForkBootstrap(rewindSHA2),+ )++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-3")++ require.NoError(t, err)+ require.Equal(t, 1, got.DeletedMessages)+ require.True(t, got.WorkspaceReset)+ require.Empty(t, got.Reason)+ require.Empty(t, port.runner.calls)+ require.Equal(t, []string{"u-1", "a-1", "u-2", "a-2"}, messageIDs(msgs.messages))+ require.NotNil(t, sessions.source.ForkBootstrap)+ require.Equal(t, rewindSHA1, sessions.source.ForkBootstrap.CommitSHA)+}++func TestRewindUnopenedForkAbandonsBootstrapWhenNoCheckpointRemains(t *testing.T) {+ history := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ svc, sessions, msgs, port := newUnopenedForkRewindFixture(+ t, history, pendingForkBootstrap(rewindSHA1),+ )+ snapshots := &fakeSnapshotDeleter{}+ svc.snapshots = snapshots++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.NoError(t, err)+ require.Equal(t, 2, got.DeletedMessages)+ require.False(t, got.WorkspaceReset)+ require.Equal(t, RewindSkipNoCheckpoint, got.Reason)+ require.Empty(t, port.runner.calls)+ require.Empty(t, msgs.messages)+ require.True(t, sessions.bootstrapCleared)+ require.Nil(t, sessions.source.ForkBootstrap)+ require.Equal(t, []string{"snap-1"}, snapshots.deleted)+ require.Empty(t, sessions.leases)+}++func TestRewindUnopenedForkKeepsSharedSnapshotWhenAbandoningBootstrap(t *testing.T) {+ history := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ svc, sessions, _, _ := newUnopenedForkRewindFixture(+ t, history, pendingForkBootstrap(rewindSHA1),+ )+ sessions.unconsumed = []*types.Session{{+ ID: "sibling", TenantID: 1,+ ForkBootstrap: pendingForkBootstrap(rewindSHA1),+ }}+ snapshots := &fakeSnapshotDeleter{}+ svc.snapshots = snapshots++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.NoError(t, err)+ require.True(t, sessions.bootstrapCleared)+ require.Empty(t, snapshots.deleted, "nested unopened sibling still needs the snapshot")+ require.Empty(t, sessions.leases)+ require.Equal(t, 2, got.DeletedMessages)+}++func TestRewindConsumedBootstrapIsLeftAloneWhenSandboxGone(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ consumedAt := forkBase.Add(time.Minute)+ bootstrap := pendingForkBootstrap(rewindSHA2)+ bootstrap.ConsumedAt = &consumedAt+ svc, sessions, _, port := newUnopenedForkRewindFixture(t, append(turn1, later...), bootstrap)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.Equal(t, RewindSkipNoSandbox, got.Reason)+ require.Empty(t, port.runner.calls)+ require.False(t, sessions.bootstrapCleared)+ require.NotNil(t, sessions.source.ForkBootstrap)+ require.Equal(t, rewindSHA2, sessions.source.ForkBootstrap.CommitSHA)+ require.True(t, sessions.source.ForkBootstrap.Consumed())+ require.Nil(t, sessions.updatedBootstrap)+}++func TestRewindLiveSandboxDoesNotRewritePendingBootstrap(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ port := newFakeRewindPort()+ sessions := newFakeSessionStore(&types.Session{+ ID: "src", TenantID: 1, UserID: "u1", Title: "分支",+ ForkBootstrap: pendingForkBootstrap(rewindSHA2),+ })+ msgs := newFakeMessageStore(append(turn1, later...))+ svc := NewSessionRewindService(sessions, msgs, port, nil, nil)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.NoError(t, err)+ require.True(t, got.WorkspaceReset)+ require.Contains(t, port.runner.calls[0], rewindSHA1)+ require.Nil(t, sessions.updatedBootstrap)+ require.Equal(t, rewindSHA2, sessions.source.ForkBootstrap.CommitSHA)+}++func TestRewindUnopenedForkBootstrapUpdateFailureDoesNotDeleteMessages(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ svc, sessions, msgs, port := newUnopenedForkRewindFixture(+ t, append(turn1, later...), pendingForkBootstrap(rewindSHA2),+ )+ sessions.updateErr = errors.New("db down")++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.Error(t, err)+ require.Nil(t, got)+ require.Contains(t, err.Error(), "db down")+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1", "u-2", "a-2"}, messageIDs(msgs.messages))+ require.Empty(t, port.runner.calls)+ require.Equal(t, rewindSHA2, sessions.source.ForkBootstrap.CommitSHA)+}++func TestRewindUnopenedForkRejectsInvalidCheckpointSHA(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", "not-a-git-object-name", 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ svc, sessions, msgs, port := newUnopenedForkRewindFixture(+ t, append(turn1, later...), pendingForkBootstrap(rewindSHA2),+ )++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")++ require.Error(t, err)+ require.Nil(t, got)+ require.Contains(t, err.Error(), "invalid")+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1", "u-2", "a-2"}, messageIDs(msgs.messages))+ require.Empty(t, port.runner.calls)+ require.Equal(t, rewindSHA2, sessions.source.ForkBootstrap.CommitSHA)+ require.Nil(t, sessions.updatedBootstrap)+}++func TestRewindBlocksLocalSendWithoutSandbox(t *testing.T) {+ turn := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ laterUser := &types.Message{+ ID: "u-2", SessionID: "src", Role: "user", CreatedAt: forkBase.Add(10 * time.Second),+ }+ port := newFakeRewindPort()+ port.bound = false+ port.boundID = ""+ svc, msgs := newRewindFixture(t, port, append(turn, laterUser))+ gate := NewSessionBusyGate()+ svc.busyGate = gate+ sessionSvc := &sessionService{busyGate: gate}++ release, err := sessionSvc.holdSandboxTurn(context.Background(), "src", "")+ require.NoError(t, err)++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-2")+ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs.deleteFromCalls)++ release()+ got, err = svc.Rewind(context.Background(), 1, "u1", "src", "u-2")+ require.NoError(t, err)+ require.Equal(t, 1, got.DeletedMessages)+}++func TestRewindConcurrentSecondIsBusy(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ port := newFakeRewindPort()+ started := make(chan struct{})+ unblock := make(chan struct{})+ var blocked atomic.Int32+ port.execBlock = func() {+ if blocked.Add(1) == 1 {+ close(started)+ <-unblock+ }+ }+ svc, msgs := newRewindFixture(t, port, append(turn1, later...))++ done := make(chan struct{})+ var firstErr error+ go func() {+ defer close(done)+ _, firstErr = svc.Rewind(context.Background(), 1, "u1", "src", "u-2")+ }()+ <-started++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "a-1")+ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)++ close(unblock)+ <-done+ require.NoError(t, firstErr)+ require.Equal(t, 1, msgs.deleteFromCalls)+}++func TestRewindLockIsSharedAcrossServiceInstances(t *testing.T) {+ turn1 := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ later := rewindCompletedTurn("u-2", "a-2", "sbx-1", rewindSHA2, 10*time.Second)+ history := append(turn1, later...)+ port := newFakeRewindPort()+ started := make(chan struct{})+ unblock := make(chan struct{})+ var blocked atomic.Int32+ port.execBlock = func() {+ if blocked.Add(1) == 1 {+ close(started)+ <-unblock+ }+ }+ svc1, _ := newRewindFixture(t, port, history)+ svc2, msgs2 := newRewindFixture(t, port, append([]*types.Message(nil), history...))++ done := make(chan struct{})+ go func() {+ defer close(done)+ _, _ = svc1.Rewind(context.Background(), 1, "u1", "src", "u-2")+ }()+ <-started++ got, err := svc2.Rewind(context.Background(), 1, "u1", "src", "a-1")+ require.ErrorIs(t, err, ErrRewindSourceBusy)+ require.Nil(t, got)+ require.Equal(t, 0, msgs2.deleteFromCalls)++ close(unblock)+ <-done+}++func TestRewindUnopenedForkBootstrapClearFailureDoesNotDeleteMessages(t *testing.T) {+ history := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ svc, sessions, msgs, _ := newUnopenedForkRewindFixture(+ t, history, pendingForkBootstrap(rewindSHA1),+ )+ sessions.clearErr = errors.New("db down")++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.Error(t, err)+ require.Nil(t, got)+ require.Contains(t, err.Error(), "db down")+ require.Equal(t, 0, msgs.deleteFromCalls)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+ require.NotNil(t, sessions.source.ForkBootstrap)+ require.False(t, sessions.bootstrapCleared)+}++func messageIDs(messages []*types.Message) []string {+ ids := make([]string, 0, len(messages))+ for _, m := range messages {+ if m != nil {+ ids = append(ids, m.ID)+ }+ }+ return ids+}++// Clearing the bootstrap column is redoable; deleting the snapshot behind it+// is not. A truncate that never lands must leave the fork something to boot+// from, otherwise the retry finds the whole transcript and no workspace.+func TestRewindKeepsForkSnapshotWhenDeleteFails(t *testing.T) {+ history := rewindCompletedTurn("u-1", "a-1", "sbx-1", rewindSHA1, 0)+ svc, sessions, msgs, _ := newUnopenedForkRewindFixture(+ t, history, pendingForkBootstrap(rewindSHA1),+ )+ snapshots := &fakeSnapshotDeleter{}+ svc.snapshots = snapshots+ msgs.deleteFromErr = errors.New("db down")++ got, err := svc.Rewind(context.Background(), 1, "u1", "src", "u-1")++ require.Error(t, err)+ require.Nil(t, got)+ require.Equal(t, []string{"u-1", "a-1"}, messageIDs(msgs.messages))+ require.Empty(t, snapshots.deleted,+ "the snapshot must survive a truncate that did not happen")+ require.True(t, sessions.bootstrapCleared,+ "the column write stays ahead of the delete so the fork cannot boot ahead of the transcript")+}diff --git a/internal/application/service/session_sandbox_turn_test.go b/internal/application/service/session_sandbox_turn_test.goindex 62f5ef1e9..c8aca3116 100644--- a/internal/application/service/session_sandbox_turn_test.go+++ b/internal/application/service/session_sandbox_turn_test.go@@ -4,6 +4,7 @@ import ("context""testing"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/stretchr/testify/require")@@ -11,7 +12,8 @@ func TestHoldSandboxTurnOpensAndClosesTheLease(t *testing.T) {holder := &turnLeaseManager{}svc := &sessionService{sandboxMgr: holder}- release := svc.holdSandboxTurn(context.Background(), "session-a", "")+ release, err := svc.holdSandboxTurn(context.Background(), "session-a", "")+ require.NoError(t, err)require.Equal(t, 1, holder.begins)require.Zero(t, holder.ends)@@ -19,16 +21,64 @@ func TestHoldSandboxTurnOpensAndClosesTheLease(t *testing.T) {require.Equal(t, 1, holder.ends)}-func TestHoldSandboxTurnIsNoopWhenBeginFails(t *testing.T) {+// A lease-store blip must not reject the user's message: only a rewind lock+// is fatal, everything else degrades to running the turn without a lease.+func TestHoldSandboxTurnDegradesWhenBeginFails(t *testing.T) {holder := &turnLeaseManager{beginErr: context.Canceled}svc := &sessionService{sandboxMgr: holder}- release := svc.holdSandboxTurn(context.Background(), "session-a", "")+ release, err := svc.holdSandboxTurn(context.Background(), "session-a", "")+ require.NoError(t, err)require.Equal(t, 1, holder.begins)release()require.Zero(t, holder.ends)}+func TestHoldSandboxTurnFailsWhenRewindLocked(t *testing.T) {+ holder := &turnLeaseManager{beginErr: sandbox.ErrSessionRewindLocked}+ svc := &sessionService{sandboxMgr: holder}++ release, err := svc.holdSandboxTurn(context.Background(), "session-a", "")+ require.ErrorIs(t, err, sandbox.ErrSessionRewindLocked)+ release()+ require.Zero(t, holder.ends)+}++func TestHoldSandboxTurnUsesBusyGateWithoutSandboxManager(t *testing.T) {+ gate := NewSessionBusyGate()+ svc := &sessionService{busyGate: gate}++ release, err := svc.holdSandboxTurn(context.Background(), "session-a", "")+ require.NoError(t, err)+ _, err = gate.TryLockRewind("session-a")+ require.ErrorIs(t, err, ErrRewindSourceBusy)++ release()+ unlock, err := gate.TryLockRewind("session-a")+ require.NoError(t, err)+ unlock()+}++func TestRejectSendIfRewindingWhenLocalGateHeld(t *testing.T) {+ gate := NewSessionBusyGate()+ svc := &sessionService{busyGate: gate}+ unlock, err := gate.TryLockRewind("session-a")+ require.NoError(t, err)++ require.ErrorIs(t, svc.RejectSendIfRewinding(context.Background(), "session-a"), sandbox.ErrSessionRewindLocked)+ unlock()+ require.NoError(t, svc.RejectSendIfRewinding(context.Background(), "session-a"))+}++func TestRejectSendIfRewindingWhenLockHeld(t *testing.T) {+ mgr := &rewindLockManager{held: true}+ svc := &sessionService{sandboxMgr: mgr}+ require.ErrorIs(t, svc.RejectSendIfRewinding(context.Background(), "session-a"), sandbox.ErrSessionRewindLocked)++ mgr.held = false+ require.NoError(t, svc.RejectSendIfRewinding(context.Background(), "session-a"))+}+type turnLeaseManager struct {stagingSandboxManagerbegins int@@ -46,3 +96,12 @@ func (m *turnLeaseManager) EndSessionTurn(context.Context, string) error {m.ends++return m.endErr}++type rewindLockManager struct {+ stagingSandboxManager+ held bool+}++func (m *rewindLockManager) HasRewindLock(context.Context, string) (bool, error) {+ return m.held, nil+}diff --git a/internal/application/service/workspace_checkpointer.go b/internal/application/service/workspace_checkpointer.goindex c2222f446..3cb46bc61 100644--- a/internal/application/service/workspace_checkpointer.go+++ b/internal/application/service/workspace_checkpointer.go@@ -1,10 +1,12 @@// Package service - per-turn /workspace git checkpoints.//// WorkspaceCheckpointer commits the session sandbox's /workspace at the end of-// every agent turn so session fork can later roll a forked sandbox back to a-// specific turn. It mirrors ArtifactCollector's shape deliberately: a narrow-// injectable interface for the sandbox side, and strict best-effort semantics-// so an auxiliary feature can never break a reply.+// every agent turn so session fork and rewind can later roll a sandbox back to+// a specific turn. Git metadata lives at sandbox.SessionGitDir, outside+// /workspace, so wiping the work tree cannot drop checkpoint history. It+// mirrors ArtifactCollector's shape deliberately: a narrow injectable+// interface for the sandbox side, and strict best-effort semantics so an+// auxiliary feature can never break a reply.//// Contract:// - Never returns an error. A failed checkpoint yields nil, the message@@ -64,28 +66,23 @@ func NewWorkspaceCheckpointer(runner SandboxShellRunner) *WorkspaceCheckpointer//// Ordering matters in two places://-// - `safe.directory` comes first. /workspace is owned by uid 1000 while-// shell_exec runs as root by default, and git refuses to touch a-// dubiously-owned repository — including from the rev-parse probe below.-// Plain assignment rather than `--add`: safe.directory is a multi-valued-// key, so --add would append one duplicate line to ~/.gitconfig per turn.+// - `safe.directory` is passed per-invocation via git_ws. /workspace is+// owned by uid 1000 while shell_exec runs as root by default, and git+// refuses to touch a dubiously-owned repository — including from the+// rev-parse probe below. -c avoids writing ~/.gitconfig every turn.//// - `--allow-empty` is mandatory. A turn that only answered a question// without touching a file would otherwise produce no commit, leaving that// message with no checkpoint and making it unusable as a fork point. With// it, every turn has exactly one checkpoint and fork boundaries are always// resolvable.-func checkpointScript(workspace, messageID string) string {+func checkpointScript(workspace, gitDir, messageID string) string {return fmt.Sprintf(`set -e-git config --global safe.directory %[1]s-git -C %[1]s rev-parse --git-dir >/dev/null 2>&1 || {- git init -q %[1]s- git -C %[1]s config user.email [email protected]- git -C %[1]s config user.name 'WeKnora Agent'-}-git -C %[1]s add -A-git -C %[1]s commit -q --allow-empty -m 'turn:%[2]s'-git -C %[1]s rev-parse HEAD`, workspace, messageID)+%s+%s+git_ws add -A+git_ws commit -q --allow-empty -m 'turn:%s'+git_ws rev-parse HEAD`, gitWorkspacePreamble(workspace, gitDir), gitWorkspaceEnsureRepo(), messageID)}// Checkpoint commits /workspace and returns the resulting checkpoint, or nil@@ -108,7 +105,7 @@ func (c *WorkspaceCheckpointer) Checkpoint(var result *sandbox.ExecuteResultvar err error- command := checkpointScript(sandbox.SessionWorkspaceRoot, messageID)+ command := checkpointScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, messageID)if runner, ok := c.runner.(sandbox.SessionInstallShellExecutor); ok {// Git operates on the existing workspace. Do not prepare artifact/input// directories or let a late checkpoint provision a replacement sandbox.diff --git a/internal/application/service/workspace_checkpointer_test.go b/internal/application/service/workspace_checkpointer_test.goindex bb5c8e372..ffd8d1c80 100644--- a/internal/application/service/workspace_checkpointer_test.go+++ b/internal/application/service/workspace_checkpointer_test.go@@ -56,13 +56,12 @@ func TestCheckpointScriptShape(t *testing.T) {script := runner.calls[0]// safe.directory must precede the rev-parse probe: the probe itself is- // what dubious-ownership blocks.+ // what dubious-ownership blocks. -c, not --add: writing global config+ // every turn would grow ~/.gitconfig (safe.directory is multi-valued).require.Less(t,strings.Index(script, "safe.directory"),strings.Index(script, "rev-parse --git-dir"),)- // Plain assignment, not --add: safe.directory is multi-valued and --add- // would append a duplicate line to ~/.gitconfig on every single turn.require.NotContains(t, script, "--add safe.directory")require.Contains(t, script, "--allow-empty")require.Contains(t, script, "turn:msg-42")@@ -70,6 +69,7 @@ func TestCheckpointScriptShape(t *testing.T) {require.NotContains(t, script, "printf 'input/\\noutput/\\n'")require.Equal(t, workspaceCheckpointTimeout, runner.timeout)require.Equal(t, sandbox.SessionWorkspaceRoot, runner.workDir)+ assertWorkspaceGitLayout(t, script)}func TestCheckpointReturnsNilWhenExecFails(t *testing.T) {diff --git a/internal/application/service/workspace_git_layout_test.go b/internal/application/service/workspace_git_layout_test.gonew file mode 100644index 000000000..e0a6a54e2--- /dev/null+++ b/internal/application/service/workspace_git_layout_test.go@@ -0,0 +1,321 @@+package service++import (+ "context"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/sandbox"+ "github.com/stretchr/testify/require"+)++func TestSessionGitDirLivesOutsideWorkspace(t *testing.T) {+ require.True(t, strings.HasPrefix(sandbox.SessionGitDir, "/"))+ require.NotEqual(t, sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir)+ require.False(t,+ strings.HasPrefix(sandbox.SessionGitDir, sandbox.SessionWorkspaceRoot+"/"),+ "checkpoint git dir %q must not live under %s",+ sandbox.SessionGitDir, sandbox.SessionWorkspaceRoot)+}++func TestCheckpointScriptUsesExternalGitDir(t *testing.T) {+ runner := &fakeShellRunner{result: &sandbox.ExecuteResult{+ ExitCode: 0, Stdout: strings.Repeat("a", 40) + "\n",+ }}+ NewWorkspaceCheckpointer(runner).Checkpoint(context.Background(), "s1", "sbx-1", "msg-1")++ require.Len(t, runner.calls, 1)+ assertWorkspaceGitLayout(t, runner.calls[0])+ require.NotContains(t, runner.calls[0], "git init -q "+sandbox.SessionWorkspaceRoot)+ require.NotContains(t, runner.calls[0], "git -C "+sandbox.SessionWorkspaceRoot)+}++func TestForkAndRewindResetScriptUsesExternalGitDir(t *testing.T) {+ script, err := workspaceResetScript(+ sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, strings.Repeat("a", 40),+ )+ require.NoError(t, err)+ assertWorkspaceGitLayout(t, script)+ require.NotContains(t, script, sandbox.SessionWorkspaceRoot+"/.git")+ require.NotContains(t, script, "git -C "+sandbox.SessionWorkspaceRoot)+}++func TestCheckpointInitLeavesGitDirOutsideWorkTree(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ require.NoError(t, os.WriteFile(filepath.Join(workspace, "keep.txt"), []byte("v1"), 0o644))+ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-1"))++ _, err := os.Stat(filepath.Join(workspace, ".git"))+ require.True(t, os.IsNotExist(err), "work tree must not grow a .git directory")+ require.FileExists(t, filepath.Join(gitDir, "HEAD"))+ body, err := os.ReadFile(filepath.Join(workspace, "keep.txt"))+ require.NoError(t, err)+ require.Equal(t, "v1", string(body))+}++func TestCheckpointKeepsAgentGitOnceWeKnoraRepoExists(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ require.NoError(t, os.WriteFile(filepath.Join(workspace, "keep.txt"), []byte("v1"), 0o644))+ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-1"))++ runGitAt(t, env, workspace, "init", "-q")+ runGitAt(t, env, workspace, "config", "user.email", "[email protected]")+ runGitAt(t, env, workspace, "config", "user.name", "Dev")+ require.NoError(t, os.WriteFile(filepath.Join(workspace, "app.txt"), []byte("mine"), 0o644))+ runGitAt(t, env, workspace, "add", "-A")+ runGitAt(t, env, workspace, "commit", "-q", "-m", "agent")+ agentHEAD := strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD"))++ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-2"))++ require.DirExists(t, filepath.Join(workspace, ".git"))+ gotAgent := strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD"))+ require.Equal(t, agentHEAD, gotAgent, "WeKnora must not delete or rewrite the agent's work-tree git")+ require.FileExists(t, filepath.Join(gitDir, "HEAD"))+ ls := runGitSplit(t, env, workspace, gitDir, "ls-files")+ require.NotContains(t, ls, ".git/", "checkpoint must not ingest the agent's .git as tracked files")+}++func TestResetPrunesLaterCommitsFromExternalGitDir(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ runGitSplit(t, env, workspace, gitDir, "init", "-q")+ runGitSplit(t, env, workspace, gitDir, "config", "user.email", "[email protected]")+ runGitSplit(t, env, workspace, gitDir, "config", "user.name", "WeKnora Agent")+ require.NoError(t, os.WriteFile(filepath.Join(workspace, "keep.txt"), []byte("early"), 0o644))+ runGitSplit(t, env, workspace, gitDir, "add", "-A")+ runGitSplit(t, env, workspace, gitDir, "commit", "-q", "-m", "early")+ early := strings.TrimSpace(runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"))+ if !gitSHAPattern.MatchString(early) {+ t.Skip("host git is not using SHA-1 object names")+ }++ require.NoError(t, os.WriteFile(filepath.Join(workspace, "secret.txt"), []byte("later-secret"), 0o644))+ runGitSplit(t, env, workspace, gitDir, "add", "-A")+ runGitSplit(t, env, workspace, gitDir, "commit", "-q", "-m", "later")+ later := strings.TrimSpace(runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"))+ require.NotEqual(t, early, later)++ script, err := workspaceResetScript(workspace, gitDir, early)+ require.NoError(t, err)+ runWorkspaceGitScript(t, env, script)++ cmd := exec.Command("git", "--git-dir", gitDir, "--work-tree", workspace, "cat-file", "-t", later)+ cmd.Env = env+ require.Error(t, cmd.Run(), "later-turn commit must be unreachable after prune")+ _, err = os.Stat(filepath.Join(workspace, "secret.txt"))+ require.True(t, os.IsNotExist(err))+ body, err := os.ReadFile(filepath.Join(workspace, "keep.txt"))+ require.NoError(t, err)+ require.Equal(t, "early", string(body))+ _, err = os.Stat(filepath.Join(workspace, ".git"))+ require.True(t, os.IsNotExist(err))+}++func TestEmptyResetWipesWorkTreeAndReinitializesGitDir(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ runGitSplit(t, env, workspace, gitDir, "init", "-q")+ runGitSplit(t, env, workspace, gitDir, "config", "user.email", "[email protected]")+ runGitSplit(t, env, workspace, gitDir, "config", "user.name", "WeKnora Agent")+ require.NoError(t, os.WriteFile(filepath.Join(workspace, "keep.txt"), []byte("early"), 0o644))+ runGitSplit(t, env, workspace, gitDir, "add", "-A")+ runGitSplit(t, env, workspace, gitDir, "commit", "-q", "-m", "early")+ early := strings.TrimSpace(runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"))+ require.NoError(t, os.WriteFile(filepath.Join(workspace, "untracked.txt"), []byte("tmp"), 0o644))++ runWorkspaceGitScript(t, env, workspaceEmptyResetScript(workspace, gitDir))++ _, err := os.Stat(filepath.Join(workspace, "keep.txt"))+ require.True(t, os.IsNotExist(err))+ _, err = os.Stat(filepath.Join(workspace, "untracked.txt"))+ require.True(t, os.IsNotExist(err))+ require.FileExists(t, filepath.Join(gitDir, "HEAD"))+ cmd := exec.Command("git", "--git-dir", gitDir, "--work-tree", workspace, "cat-file", "-t", early)+ cmd.Env = env+ require.Error(t, cmd.Run(), "pre-rewind commits must be unreachable after prune")+ _, err = os.Stat(filepath.Join(workspace, ".git"))+ require.True(t, os.IsNotExist(err))+}++func TestCheckpointSurvivesWipedWorkTree(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ require.NoError(t, os.WriteFile(filepath.Join(workspace, "keep.txt"), []byte("v1"), 0o644))+ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-1"))+ first := strings.TrimSpace(runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"))++ require.NoError(t, os.RemoveAll(workspace))+ _, err := os.Stat(filepath.Join(workspace, ".git"))+ require.True(t, os.IsNotExist(err))++ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-2"))++ require.DirExists(t, workspace)+ _, err = os.Stat(filepath.Join(workspace, ".git"))+ require.True(t, os.IsNotExist(err))+ got := strings.TrimSpace(runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"))+ require.NotEqual(t, first, got)+ require.Equal(t, "commit", strings.TrimSpace(+ runGitSplit(t, env, workspace, gitDir, "cat-file", "-t", first),+ ), "wiping /workspace must not drop earlier checkpoint objects")+}++func assertWorkspaceGitLayout(t *testing.T, script string) {+ t.Helper()+ require.Contains(t, script, "--git-dir=")+ require.Contains(t, script, sandbox.SessionGitDir)+ require.Contains(t, script, "--work-tree=")+ require.Contains(t, script, sandbox.SessionWorkspaceRoot)+ require.NotContains(t, script, sandbox.SessionWorkspaceRoot+"/.git")+}++func requireGit(t *testing.T) {+ t.Helper()+ if _, err := exec.LookPath("git"); err != nil {+ t.Skip("git not available")+ }+}++func splitGitDirs(t *testing.T) (workspace, gitDir string, env []string) {+ t.Helper()+ workspace = filepath.Join(t.TempDir(), "workspace")+ gitDir = filepath.Join(t.TempDir(), "workspace.git")+ require.NoError(t, os.MkdirAll(workspace, 0o755))+ return workspace, gitDir, isolatedGitEnv(t)+}++func runWorkspaceGitScript(t *testing.T, env []string, script string) {+ t.Helper()+ cmd := exec.Command("bash", "-c", script)+ cmd.Env = env+ out, err := cmd.CombinedOutput()+ require.NoError(t, err, string(out))+}++func runGitAt(t *testing.T, env []string, dir string, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)+ cmd.Env = env+ out, err := cmd.CombinedOutput()+ require.NoError(t, err, string(out))+ return string(out)+}++func runGitSplit(t *testing.T, env []string, workspace, gitDir string, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", append([]string{+ "--git-dir", gitDir, "--work-tree", workspace,+ }, args...)...)+ cmd.Env = env+ out, err := cmd.CombinedOutput()+ require.NoError(t, err, string(out))+ return string(out)+}++// A sandbox provisioned before GIT_DIR moved out of /workspace still has its+// checkpoints in the work tree, and the SHAs on those turns only resolve+// there. Rewind and fork must still be able to reset to them.+func TestAdoptsLegacyWorkTreeCheckpointRepo(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ // The pre-move layout: checkpoints committed into $WORK_TREE/.git under+ // the checkpointer's identity.+ runGitAt(t, env, workspace, "init", "-q")+ runGitAt(t, env, workspace, "config", "user.email", "[email protected]")+ runGitAt(t, env, workspace, "config", "user.name", "WeKnora Agent")+ require.NoError(t, os.WriteFile(filepath.Join(workspace, "keep.txt"), []byte("early"), 0o644))+ runGitAt(t, env, workspace, "add", "-A")+ runGitAt(t, env, workspace, "commit", "-q", "-m", "turn:msg-1")+ legacy := strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD"))+ if !gitSHAPattern.MatchString(legacy) {+ t.Skip("host git is not using SHA-1 object names")+ }++ require.NoError(t, os.WriteFile(filepath.Join(workspace, "later.txt"), []byte("later"), 0o644))+ runGitAt(t, env, workspace, "add", "-A")+ runGitAt(t, env, workspace, "commit", "-q", "-m", "turn:msg-2")++ script, err := workspaceResetScript(workspace, gitDir, legacy)+ require.NoError(t, err)+ runWorkspaceGitScript(t, env, script)++ require.FileExists(t, filepath.Join(gitDir, "HEAD"), "legacy repo must move to the new git dir")+ _, statErr := os.Stat(filepath.Join(workspace, ".git"))+ require.True(t, os.IsNotExist(statErr), "adopted repo must not be left in the work tree")+ require.Equal(t, legacy, strings.TrimSpace(+ runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"),+ ), "reset must land on the pre-move checkpoint instead of failing on a bad object")+ body, err := os.ReadFile(filepath.Join(workspace, "keep.txt"))+ require.NoError(t, err)+ require.Equal(t, "early", string(body))+ _, statErr = os.Stat(filepath.Join(workspace, "later.txt"))+ require.True(t, os.IsNotExist(statErr))+}++// Adoption keys on the checkpointer's committer identity, so a repository the+// agent created for its own work in /workspace is never swallowed.+func TestDoesNotAdoptAgentOwnedWorkTreeRepo(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ runGitAt(t, env, workspace, "init", "-q")+ runGitAt(t, env, workspace, "config", "user.email", "[email protected]")+ runGitAt(t, env, workspace, "config", "user.name", "Dev")+ require.NoError(t, os.WriteFile(filepath.Join(workspace, "app.txt"), []byte("mine"), 0o644))+ runGitAt(t, env, workspace, "add", "-A")+ runGitAt(t, env, workspace, "commit", "-q", "-m", "agent")+ agentHEAD := strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD"))++ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-1"))++ require.DirExists(t, filepath.Join(workspace, ".git"))+ require.Equal(t, agentHEAD, strings.TrimSpace(+ runGitAt(t, env, workspace, "rev-parse", "HEAD"),+ ), "the agent's own repository must be left exactly as it was")+ require.FileExists(t, filepath.Join(gitDir, "HEAD"))+ require.NotEqual(t, agentHEAD, strings.TrimSpace(+ runGitSplit(t, env, workspace, gitDir, "rev-parse", "HEAD"),+ ))+}++// Once adopted, the work tree has no .git left, so a later turn must not try+// to adopt anything again.+func TestAdoptionIsOnlyAttemptedWhileTheNewGitDirIsMissing(t *testing.T) {+ requireGit(t)+ workspace, gitDir, env := splitGitDirs(t)++ runGitAt(t, env, workspace, "init", "-q")+ runGitAt(t, env, workspace, "config", "user.email", "[email protected]")+ runGitAt(t, env, workspace, "config", "user.name", "WeKnora Agent")+ runGitAt(t, env, workspace, "commit", "-q", "--allow-empty", "-m", "turn:msg-0")+ legacy := strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD"))++ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-1"))+ require.Equal(t, "commit", strings.TrimSpace(+ runGitSplit(t, env, workspace, gitDir, "cat-file", "-t", legacy),+ ), "the adopted history must still be reachable")++ // The agent now starts its own repository in the work tree.+ runGitAt(t, env, workspace, "init", "-q")+ runGitAt(t, env, workspace, "config", "user.email", "[email protected]")+ runGitAt(t, env, workspace, "config", "user.name", "WeKnora Agent")+ runGitAt(t, env, workspace, "commit", "-q", "--allow-empty", "-m", "agent")+ agentHEAD := strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD"))++ runWorkspaceGitScript(t, env, checkpointScript(workspace, gitDir, "msg-2"))++ require.DirExists(t, filepath.Join(workspace, ".git"))+ require.Equal(t, agentHEAD, strings.TrimSpace(runGitAt(t, env, workspace, "rev-parse", "HEAD")))+}diff --git a/internal/application/service/workspace_reset.go b/internal/application/service/workspace_reset.gonew file mode 100644index 000000000..ca98e02af--- /dev/null+++ b/internal/application/service/workspace_reset.go@@ -0,0 +1,186 @@+// Package service - rolling a session sandbox's /workspace back to a commit.+//+// Two callers share this: ForkBootstrapper rolls a forked session's first+// sandbox back to the fork point, and SessionRewindService rolls the session's+// own live sandbox back to a rewind point. Both need identical semantics, so+// the script and the exec wrapper live here rather than in either one.+package service++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/Tencent/WeKnora/internal/sandbox"+)++// workspaceResetTimeout bounds the git rollback. clean -fdx may delete a large+// untracked tree, and gc --prune=now walks leftover objects from later turns,+// so this is more generous than the per-turn checkpoint.+const workspaceResetTimeout = 90 * time.Second++// workspaceResetScript renders the rollback of workspace to sha.+//+// reset --hard restores tracked files (including input/ and output/). Other+// refs, ORIG_HEAD, and reflogs still name later-turn commits, so those are+// deleted and gc'd before clean -fdx; otherwise the working tree would look+// right while `git checkout` could resurrect later files. -x then drops+// leftover untracked files that are not in that commit.+func workspaceResetScript(workspace, gitDir, sha string) (string, error) {+ if !gitSHAPattern.MatchString(sha) {+ return "", fmt.Errorf("workspace reset: invalid commit sha %q", truncateForLog(sha))+ }+ return "set -e\n" + gitWorkspacePreamble(workspace, gitDir) ++ "git_ws reset --hard " + sha + "\n" ++ gitWorkspacePruneAndClean(), nil+}++// workspaceEmptyResetScript is the start-over path: kept history has no SHA,+// so we commit an empty tree and run the same reset+prune+clean as a SHA rewind.+func workspaceEmptyResetScript(workspace, gitDir string) string {+ return "set -e\n" + gitWorkspacePreamble(workspace, gitDir) + gitWorkspaceEnsureRepo() + `+empty=$(git_ws commit-tree "$(git_ws mktree </dev/null)" -m 'rewind: empty')+git_ws reset --hard "$empty"+` + gitWorkspacePruneAndClean()+}++// gitWorkspaceEnsureRepo is the checkpointer's first-use init. Empty rewind+// reuses it so a sandbox that never checkpointed can still reset to empty.+func gitWorkspaceEnsureRepo() string {+ return `git_ws rev-parse --git-dir >/dev/null 2>&1 || {+ mkdir -p "$(dirname "$GIT_DIR")"+ git_ws init -q+ git_ws config user.email [email protected]+ git_ws config user.name 'WeKnora Agent'+}+`+}++func gitWorkspacePruneAndClean() string {+ return `current=$(git_ws symbolic-ref -q HEAD || true)+for ref in $(git_ws for-each-ref --format='%(refname)'); do+ [ -z "$ref" ] && continue+ [ "$ref" = "$current" ] && continue+ git_ws update-ref -d "$ref"+done+rm -f "$GIT_DIR"/ORIG_HEAD "$GIT_DIR"/FETCH_HEAD+git_ws reflog expire --expire=now --all+git_ws gc --prune=now+git_ws clean -fdx+`+}++// gitWorkspacePreamble is shared by checkpoint and reset so fork and rewind+// cannot drift onto different git layouts. GIT_DIR is outside /workspace;+// --work-tree still edits the session files.+func gitWorkspacePreamble(workspace, gitDir string) string {+ return fmt.Sprintf(`WORK_TREE=%[1]s+GIT_DIR=%[2]s+git_ws() {+ git -c safe.directory='*' --git-dir="$GIT_DIR" --work-tree="$WORK_TREE" "$@"+}+mkdir -p "$WORK_TREE"+`, shellSingleQuote(workspace), shellSingleQuote(gitDir)) + gitWorkspaceAdoptLegacyRepo()+}++// gitWorkspaceAdoptLegacyRepo migrates a sandbox that still keeps its+// checkpoints in the work tree.+//+// Before GIT_DIR moved out of /workspace, checkpoints committed into+// $WORK_TREE/.git, and the SHAs recorded on those turns only resolve there.+// Without this, a sandbox provisioned before the move would find no repo at+// the new path, start an empty one, and then fail every fork or rewind that+// targets a pre-move checkpoint with "bad object".+//+// It runs in the shared preamble so checkpoint, reset and empty reset all+// adopt the old store. Two guards keep it from touching anything else: the+// new GIT_DIR must be absent (a migrated sandbox never re-enters this), and+// the work-tree repo must carry the checkpointer's committer identity, so an+// agent's own `git init` in /workspace is left alone.+func gitWorkspaceAdoptLegacyRepo() string {+ return `if ! git_ws rev-parse --git-dir >/dev/null 2>&1; then+ legacy_git_dir="$WORK_TREE/.git"+ legacy_owner=$(git -c safe.directory='*' --git-dir="$legacy_git_dir" config user.email 2>/dev/null || true)+ if [ "$legacy_owner" = [email protected] ]; then+ mkdir -p "$(dirname "$GIT_DIR")"+ mv "$legacy_git_dir" "$GIT_DIR"+ fi+fi+`+}++func shellSingleQuote(s string) string {+ return "'" + strings.ReplaceAll(s, `'`, `'"'"'`) + "'"+}++func gitResetFailure(sha, stderr string) error {+ return fmt.Errorf("workspace reset: git reset to %s failed: %s", sha, stderr)+}++func execWorkspaceReset(+ ctx context.Context, runner SandboxShellRunner, sessionID, script, expectedSandboxID string,+) (*sandbox.ExecuteResult, error) {+ if runner == nil {+ return nil, errors.New("workspace reset: no shell runner wired")+ }+ if withOpts, ok := runner.(sandbox.SessionInstallShellExecutor); ok {+ return withOpts.ExecShellCommandWithOptions(ctx, sessionID, script, sandbox.ShellExecOptions{+ WorkDir: sandbox.SessionWorkspaceRoot,+ Timeout: workspaceResetTimeout,+ SkipWorkspacePrep: true,+ ExpectedSandboxID: expectedSandboxID,+ })+ }+ return runner.ExecShellCommand(+ ctx, sessionID, script, sandbox.SessionWorkspaceRoot, workspaceResetTimeout, nil,+ )+}++// resetWorkspaceToCommit rolls the session's live /workspace back to sha+// through a session-scoped shell runner.+//+// Callers that already hold a sandbox handle (the fork bootstrapper, which+// runs under the lifecycle lock and must not Resolve) exec the script+// themselves; everyone else goes through the runner. expectedSandboxID makes+// that path lookup-only so rewind cannot provision a replacement VM.+func resetWorkspaceToCommit(+ ctx context.Context, runner SandboxShellRunner, sessionID, sha, expectedSandboxID string,+) error {+ sha = strings.TrimSpace(sha)+ script, err := workspaceResetScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir, sha)+ if err != nil {+ return err+ }+ result, err := execWorkspaceReset(ctx, runner, sessionID, script, expectedSandboxID)+ if err != nil {+ return fmt.Errorf("workspace reset: git reset exec: %w", err)+ }+ if result == nil || result.ExitCode != 0 {+ stderr := ""+ if result != nil {+ stderr = result.Stderr+ }+ return gitResetFailure(sha, stderr)+ }+ return nil+}++func resetWorkspaceToEmpty(+ ctx context.Context, runner SandboxShellRunner, sessionID, expectedSandboxID string,+) error {+ script := workspaceEmptyResetScript(sandbox.SessionWorkspaceRoot, sandbox.SessionGitDir)+ result, err := execWorkspaceReset(ctx, runner, sessionID, script, expectedSandboxID)+ if err != nil {+ return fmt.Errorf("workspace reset: empty workspace exec: %w", err)+ }+ if result == nil || result.ExitCode != 0 {+ stderr := ""+ if result != nil {+ stderr = result.Stderr+ }+ return fmt.Errorf("workspace reset: empty workspace failed: %s", stderr)+ }+ return nil+}diff --git a/internal/container/container.go b/internal/container/container.goindex a1d429a6f..c388e91a9 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -387,6 +387,20 @@ func BuildContainer(container *dig.Container) *dig.Container {return pinned}))must(container.Provide(service.NewSessionForkServiceFromRepos))+ must(container.Provide(func(+ mgr sandbox.Manager,+ pinned *service.PinnedSessionSandbox,+ ) service.SessionRewindSandboxPort {+ if port, ok := mgr.(service.SessionRewindSandboxPort); ok {+ return port+ }+ if pinned == nil {+ return nil+ }+ return pinned+ }))+ must(container.Provide(service.NewSessionBusyGate))+ must(container.Provide(service.NewSessionRewindServiceFromRepos))// SandboxTerminalService opens interactive PTYs on session sandboxes for// the frontend terminal panel. First-use provisioning takes a sandboxdiff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.goindex 806ca04ea..ca2ab5043 100644--- a/internal/handler/session/handler.go+++ b/internal/handler/session/handler.go@@ -65,6 +65,9 @@ type Handler struct {// forkService branches a session at a chosen user message. May be nil in// deployments where fork is not wired; ForkSession checks.forkService sessionForker+ // rewindService truncates the current session at a chosen message. May+ // be nil in deployments where rewind is not wired; RewindSession checks.+ rewindService sessionRewinder}// NewHandler creates a new instance of Handler with all necessary dependencies@@ -99,6 +102,7 @@ func NewHandler(desktopLast service.SandboxDesktopLastStore,rdb *redis.Client,forkService *service.SessionForkService,+ rewindService *service.SessionRewindService,) *Handler {h := &Handler{browserSkill: browserSkill,@@ -138,6 +142,9 @@ func NewHandler(if forkService != nil {h.forkService = forkService}+ if rewindService != nil {+ h.rewindService = rewindService+ }return h}diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.goindex 394fdd298..f816475a0 100644--- a/internal/handler/session/qa.go+++ b/internal/handler/session/qa.go@@ -19,6 +19,7 @@ import ("github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/event""github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/sandbox""github.com/Tencent/WeKnora/internal/storageurl""github.com/Tencent/WeKnora/internal/stream""github.com/Tencent/WeKnora/internal/tracing/langfuse"@@ -91,6 +92,9 @@ type qaRequestContext struct {// previous run are visible to this engine from round 1 and to any client// that reloads the queue.steerCarryOver []interfaces.StreamEvent+ // turnLeaseHeld records that executeQA already took the send-side turn+ // lease for this request, so the QA service does not take a second one.+ turnLeaseHeld bool}// buildQARequest converts the qaRequestContext into a types.QARequest for service invocation.@@ -117,6 +121,7 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest {LocalBrowserEnabled: rc.localBrowserEnabled,Attachments: rc.attachments,QuestionOrigin: rc.questionOrigin,+ TurnLeaseHeld: rc.turnLeaseHeld,}if rc.steerSink != nil {req.SteerSink = rc.steerSink@@ -662,6 +667,10 @@ type sseStreamContext struct {// second turn.liveRunFailed boolliveRunErr error+ // releaseTurn ends the sandbox turn lease taken before persist. Knowledge+ // mode releases on completion (the pipeline returns before the stream+ // finishes); agent mode releases when AgentQA returns.+ releaseTurn func()}// setupSSEStream sets up the SSE streaming context@@ -1073,6 +1082,65 @@ func (h *Handler) rejectIfOtherAgentRunLive(ctx context.Context, reqCtx *qaRequereturn errors.NewConflictError("another turn is already running in this session")}+func (h *Handler) rejectIfSessionRewinding(ctx context.Context, sessionID string) error {+ type rewindSendGuard interface {+ RejectSendIfRewinding(context.Context, string) error+ }+ guard, ok := h.sessionService.(rewindSendGuard)+ if !ok {+ return nil+ }+ err := guard.RejectSendIfRewinding(ctx, sessionID)+ if err == nil {+ return nil+ }+ if stderrors.Is(err, sandbox.ErrSessionRewindLocked) {+ return errors.NewConflictError("session rewind is in progress")+ }+ return errors.NewInternalServerError(err.Error())+}++func (h *Handler) holdQATurn(ctx context.Context, reqCtx *qaRequestContext) (func(), bool) {+ noop := func() {}+ if reqCtx == nil {+ return noop, true+ }+ type sessionTurnHolder interface {+ HoldSandboxTurn(context.Context, string, string) (func(), error)+ }+ holder, ok := h.sessionService.(sessionTurnHolder)+ if !ok {+ return noop, true+ }+ configID := ""+ if reqCtx.customAgent != nil {+ configID = reqCtx.customAgent.Config.SandboxConfigID+ }+ release, err := holder.HoldSandboxTurn(ctx, reqCtx.sessionID, configID)+ if err == nil {+ // The QA service reads this off the built request and skips its own+ // hold, so the send path opens and closes the lease exactly once.+ reqCtx.turnLeaseHeld = true+ }+ if err != nil {+ if reqCtx.c != nil && !reqCtx.skipSSE {+ if stderrors.Is(err, sandbox.ErrSessionRewindLocked) || stderrors.Is(err, sandbox.ErrSessionTurnActive) {+ _ = reqCtx.c.Error(errors.NewConflictError("session rewind is in progress"))+ } else {+ _ = reqCtx.c.Error(errors.NewInternalServerError(err.Error()))+ }+ } else {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": reqCtx.sessionID})+ }+ return noop, false+ }+ if release == nil {+ release = noop+ }+ var once sync.Once+ return func() { once.Do(release) }, true+}+// executeQA is the unified execution flow for both KnowledgeQA and AgentQA modes.// It handles message creation, SSE setup, VLM analysis, service invocation, and error handling.func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle bool) {@@ -1096,6 +1164,19 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitlereturn}}+ if err := h.rejectIfSessionRewinding(ctx, sessionID); err != nil {+ if reqCtx.c != nil && !reqCtx.skipSSE {+ _ = reqCtx.c.Error(err)+ } else {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})+ }+ return+ }++ releaseQATurn, held := h.holdQATurn(ctx, reqCtx)+ if !held {+ return+ }// Agent mode: emit agent query event before message creationif mode == qaModeAgent {@@ -1109,6 +1190,7 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitleRequestID: reqCtx.requestID,},}); err != nil {+ releaseQATurn()logger.Errorf(ctx, "Failed to emit agent query event: %v", err)return}@@ -1120,6 +1202,7 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle// Create user message. Include pre-uploaded document metadata so history// reload shows the attachments even though their content is selected later.if err := h.persistTurnMessages(ctx, reqCtx); err != nil {+ releaseQATurn()if reqCtx.c != nil && !reqCtx.skipSSE {_ = reqCtx.c.Error(errors.NewInternalServerError(err.Error()))} else {@@ -1148,10 +1231,12 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle// Setup SSE streamstreamCtx := h.setupSSEStream(reqCtx, generateTitle, mode)+ streamCtx.releaseTurn = releaseQATurnif streamCtx.liveRunFailed {if streamCtx.cancel != nil {streamCtx.cancel()}+ releaseQATurn()h.rollbackTurnMessages(ctx, reqCtx, createdUser, createdAssistant)if reqCtx.c != nil && !reqCtx.skipSSE {if stderrors.Is(streamCtx.liveRunErr, stream.ErrLiveRunExists) {@@ -1215,6 +1300,9 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitledefer close(asyncDone)defer func() {if r := recover(); r != nil {+ if streamCtx.releaseTurn != nil {+ streamCtx.releaseTurn()+ }buf := make([]byte, 10240)runtime.Stack(buf, true)stageName := "Knowledge QA"@@ -1227,6 +1315,9 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle}// Agent mode: complete the assistant message in defer (normal mode does it via event handler)if mode == qaModeAgent {+ if streamCtx.releaseTurn != nil {+ streamCtx.releaseTurn()+ }// Use WithoutCancel so a user-triggered stop (which cancels// asyncCtx) doesn't also cancel the GORM UPDATE that persists// AgentSteps/Content. Without this, cancelled-ctx makes@@ -1272,6 +1363,12 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle}logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)}+ // Knowledge mode normally releases on EventAgentFinalAnswer Done.+ // If that event never fires, release here so rewind is not blocked+ // until the Redis turn TTL expires.+ if mode == qaModeNormal && streamCtx.releaseTurn != nil {+ streamCtx.releaseTurn()+ }}()// Resolve pre-uploaded attachments (may still be parsing): waits with a@@ -1295,6 +1392,9 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle}if serviceErr != nil {+ if mode == qaModeNormal && streamCtx.releaseTurn != nil {+ streamCtx.releaseTurn()+ }// A user-requested stop cancels asyncCtx, which surfaces here as a// context cancellation. That is an expected outcome, not a failure:// the stop event already notifies the client, so don't emit a@@ -1701,6 +1801,9 @@ func (h *Handler) completeQuickAnswerTurn(})}h.completeAssistantMessage(ctx, streamCtx.assistantMessage, query, userMessageID)+ if streamCtx.releaseTurn != nil {+ streamCtx.releaseTurn()+ }}// sessionTenantInfoContext makes the tenant info match the session owner (thediff --git a/internal/handler/session/rewind.go b/internal/handler/session/rewind.gonew file mode 100644index 000000000..d7c3a1c57--- /dev/null+++ b/internal/handler/session/rewind.go@@ -0,0 +1,127 @@+package session++import (+ "context"+ stderrors "errors"+ "net/http"+ "strings"++ "github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/gin-gonic/gin"+)++// sessionRewinder is the rewind surface the handler needs. Declaring it here+// rather than depending on *service.SessionRewindService keeps the handler+// testable with a stub.+type sessionRewinder interface {+ Rewind(+ ctx context.Context,+ tenantID uint64,+ userID, sessionID, messageID string,+ ) (*service.RewindResult, error)+}++// RewindSessionRequest is the rewind endpoint's body.+type RewindSessionRequest struct {+ // MessageID is the message to rewind to. A user message deletes itself and+ // everything after (the client prefills that question). An assistant+ // message keeps itself and deletes everything after.+ MessageID string `json:"message_id" binding:"required"`+}++// RewindSession godoc+// @Summary 回滚会话+// @Description 回滚当前会话到指定用户或助手消息:删除其后消息,可到达时 git reset 工作区。+// @Tags 会话+// @Accept json+// @Produce json+// @Param session_id path string true "会话 ID"+// @Param request body RewindSessionRequest true "回滚请求"+// @Success 200 {object} map[string]interface{} "回滚结果"+// @Failure 400 {object} errors.AppError "请求参数错误 / 回滚点角色不支持"+// @Failure 404 {object} errors.AppError "会话或消息不存在"+// @Failure 409 {object} errors.AppError "会话正在生成中 / 无检查点 / 沙箱已更换"+// @Failure 500 {object} errors.AppError "工作区回滚失败"+// @Security Bearer+// @Security ApiKeyAuth+// @Router /sessions/{session_id}/rewind [post]+func (h *Handler) RewindSession(c *gin.Context) {+ ctx := c.Request.Context()++ sessionID := strings.TrimSpace(c.Param("session_id"))+ if sessionID == "" {+ sessionID = strings.TrimSpace(c.Param("id"))+ }+ if sessionID == "" {+ _ = c.Error(errors.NewBadRequestError("session ID is required"))+ return+ }++ var req RewindSessionRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ _ = c.Error(errors.NewBadRequestError("message_id is required"))+ return+ }+ if strings.TrimSpace(req.MessageID) == "" {+ _ = c.Error(errors.NewBadRequestError("message_id is required"))+ return+ }++ if h.rewindService == nil {+ _ = c.Error(errors.NewServiceUnavailableError("session rewind is not available"))+ return+ }++ tenantID, _ := types.TenantIDFromContext(ctx)+ userID := types.SessionOwnerIDFromContext(ctx)++ result, err := h.rewindService.Rewind(+ ctx, tenantID, userID, sessionID, strings.TrimSpace(req.MessageID),+ )+ if err != nil {+ if stderrors.Is(err, service.ErrRewindSourceBusy) {+ c.JSON(http.StatusConflict, gin.H{+ "success": false,+ "error": "session has an active turn",+ "code": "REWIND_SOURCE_BUSY",+ })+ return+ }+ if stderrors.Is(err, service.ErrRewindNoCheckpoint) {+ c.JSON(http.StatusConflict, gin.H{+ "success": false,+ "error": "no reachable workspace checkpoint",+ "code": "REWIND_NO_CHECKPOINT",+ })+ return+ }+ if stderrors.Is(err, service.ErrRewindSandboxReplaced) {+ c.JSON(http.StatusConflict, gin.H{+ "success": false,+ "error": "sandbox was replaced",+ "code": "REWIND_SANDBOX_REPLACED",+ })+ return+ }+ if stderrors.Is(err, service.ErrRewindSessionNotFound) {+ _ = c.Error(errors.NewNotFoundError("session not found"))+ return+ }+ if stderrors.Is(err, service.ErrRewindMessageNotFound) {+ _ = c.Error(errors.NewNotFoundError("message not found"))+ return+ }+ if stderrors.Is(err, service.ErrRewindMessageRole) {+ _ = c.Error(errors.NewBadRequestError("rewind point must be a user or assistant message"))+ return+ }+ logger.Errorf(ctx, "rewind session %s failed: %v", sessionID, err)+ _ = c.Error(errors.NewInternalServerError("rewind session failed"))+ return+ }++ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})+}diff --git a/internal/handler/session/rewind_test.go b/internal/handler/session/rewind_test.gonew file mode 100644index 000000000..cbc2da109--- /dev/null+++ b/internal/handler/session/rewind_test.go@@ -0,0 +1,137 @@+package session++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/middleware"+ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"+)++type stubRewinder struct {+ result *service.RewindResult+ err error+ gotMsg string+}++func (s *stubRewinder) Rewind(+ _ context.Context, _ uint64, _, _, messageID string,+) (*service.RewindResult, error) {+ s.gotMsg = messageID+ return s.result, s.err+}++func performRewind(t *testing.T, rewinder sessionRewinder, body string) *httptest.ResponseRecorder {+ t.Helper()+ gin.SetMode(gin.TestMode)+ h := &Handler{rewindService: rewinder}++ w := httptest.NewRecorder()+ r := gin.New()+ r.Use(middleware.ErrorHandler())+ r.POST("/sessions/:session_id/rewind", h.RewindSession)+ req := httptest.NewRequest(http.MethodPost, "/sessions/src/rewind", bytes.NewBufferString(body))+ req.Header.Set("Content-Type", "application/json")+ r.ServeHTTP(w, req)+ return w+}++func TestRewindSessionReturnsCounts(t *testing.T) {+ rewinder := &stubRewinder{result: &service.RewindResult{+ DeletedMessages: 4, WorkspaceReset: true,+ }}++ w := performRewind(t, rewinder, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusOK, w.Code)+ require.Equal(t, "u-2", rewinder.gotMsg)++ var body map[string]any+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ data := body["data"].(map[string]any)+ require.Equal(t, float64(4), data["deleted_messages"])+ require.Equal(t, true, data["workspace_reset"])+ require.Equal(t, "", data["reason"])+}++func TestRewindSessionSurfacesSkipReason(t *testing.T) {+ rewinder := &stubRewinder{result: &service.RewindResult{+ DeletedMessages: 2, WorkspaceReset: false, Reason: service.RewindSkipNoCheckpoint,+ }}++ w := performRewind(t, rewinder, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusOK, w.Code)+ var body map[string]any+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ data := body["data"].(map[string]any)+ require.Equal(t, false, data["workspace_reset"])+ require.Equal(t, "NO_CHECKPOINT", data["reason"])+}++func TestRewindSessionRejectsMissingMessageID(t *testing.T) {+ rewinder := &stubRewinder{result: &service.RewindResult{DeletedMessages: 1}}++ w := performRewind(t, rewinder, `{}`)++ require.Equal(t, http.StatusBadRequest, w.Code)+}++func TestRewindSessionMapsUnsupportedRoleTo400(t *testing.T) {+ rewinder := &stubRewinder{err: service.ErrRewindMessageRole}++ w := performRewind(t, rewinder, `{"message_id":"sys-1"}`)++ require.Equal(t, http.StatusBadRequest, w.Code)+}++func TestRewindSessionMapsMissingSessionTo404(t *testing.T) {+ rewinder := &stubRewinder{err: service.ErrRewindSessionNotFound}++ w := performRewind(t, rewinder, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusNotFound, w.Code)+}++func TestRewindSessionMapsBusySourceTo409(t *testing.T) {+ rewinder := &stubRewinder{err: service.ErrRewindSourceBusy}++ w := performRewind(t, rewinder, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusConflict, w.Code)+ var body map[string]any+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ require.Equal(t, "REWIND_SOURCE_BUSY", body["code"])+}++func TestRewindSessionMapsReplacedSandboxTo409(t *testing.T) {+ rewinder := &stubRewinder{err: service.ErrRewindSandboxReplaced}++ w := performRewind(t, rewinder, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusConflict, w.Code)+ var body map[string]any+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))+ require.Equal(t, "REWIND_SANDBOX_REPLACED", body["code"])+}++func TestRewindSessionUnavailableWhenUnwired(t *testing.T) {+ w := performRewind(t, nil, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusServiceUnavailable, w.Code)+}++func TestRewindSessionMapsResetFailureTo500(t *testing.T) {+ rewinder := &stubRewinder{err: errors.New("workspace reset: git reset exec: sandbox unreachable")}++ w := performRewind(t, rewinder, `{"message_id":"u-2"}`)++ require.Equal(t, http.StatusInternalServerError, w.Code)+}diff --git a/internal/router/routes_chat.go b/internal/router/routes_chat.goindex 1f8bc8722..43f06bcf0 100644--- a/internal/router/routes_chat.go+++ b/internal/router/routes_chat.go@@ -65,6 +65,7 @@ func RegisterSessionRoutes(sessions.DELETE("/:id/attachments/:attachment_id", handler.DeleteTemporaryDocument)sessions.POST("/:session_id/stop", handler.StopSession)sessions.POST("/:session_id/fork", handler.ForkSession)+ sessions.POST("/:session_id/rewind", handler.RewindSession)sessions.POST("/:session_id/sandbox/terminal-ticket", handler.IssueSandboxTerminalTicket)sessions.POST("/:session_id/sandbox/desktop-ticket", handler.IssueSandboxDesktopTicket)sessions.POST("/:session_id/sandbox/desktop/activity", handler.ReportSandboxDesktopActivity)diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.goindex ac3e74ef2..2091e895a 100644--- a/internal/sandbox/sandbox.go+++ b/internal/sandbox/sandbox.go@@ -158,6 +158,11 @@ var (// again; the UI must get an explicit click first. Distinct from// ErrNoLiveSessionSandbox, which means there is no binding to resume.ErrSandboxPaused = errors.New("session sandbox is paused")+ // ErrSessionRewindLocked means another rewind already holds the session.+ ErrSessionRewindLocked = errors.New("sandbox: session rewind already in progress")+ // ErrSessionTurnActive means a chat turn already holds the session lease,+ // so rewind must not take the exclusive lock or reset the workspace.+ ErrSessionTurnActive = errors.New("sandbox: session turn is active")// ErrTerminalUnsupported is returned when the active backend cannot// stream PTYs (Docker, a disabled manager). Distinct from// ErrNoLiveSessionSandbox: the session may well have a live sandbox,diff --git a/internal/sandbox/session_binding.go b/internal/sandbox/session_binding.goindex 28c365349..5661a15ce 100644--- a/internal/sandbox/session_binding.go+++ b/internal/sandbox/session_binding.go@@ -294,6 +294,7 @@ type MemorySessionSandboxBindingStore struct {bindings map[SessionSandboxKey]SessionSandboxBindinglocks map[SessionSandboxKey]*memoryLifecycleLockturns map[SessionSandboxKey]*memoryTurnLease+ rewinds map[SessionSandboxKey]struct{}}// NewMemorySessionSandboxBindingStore creates an empty in-memory store.@@ -302,6 +303,7 @@ func NewMemorySessionSandboxBindingStore() *MemorySessionSandboxBindingStore {bindings: make(map[SessionSandboxKey]SessionSandboxBinding),locks: make(map[SessionSandboxKey]*memoryLifecycleLock),turns: make(map[SessionSandboxKey]*memoryTurnLease),+ rewinds: make(map[SessionSandboxKey]struct{}),}}@@ -539,6 +541,9 @@ func (s *MemorySessionSandboxBindingStore) BeginTurn(}s.mu.Lock()defer s.mu.Unlock()+ if _, held := s.rewinds[key]; held {+ return ErrSessionRewindLocked+ }lease := s.turns[key]if lease == nil {lease = &memoryTurnLease{}@@ -573,6 +578,53 @@ func (s *MemorySessionSandboxBindingStore) EndTurn(return nil}+// TryLockRewind takes a process-local exclusive rewind lock for key.+func (s *MemorySessionSandboxBindingStore) TryLockRewind(+ ctx context.Context,+ key SessionSandboxKey,+) (func(), error) {+ if err := key.Validate(); err != nil {+ return nil, err+ }+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.rewinds == nil {+ s.rewinds = make(map[SessionSandboxKey]struct{})+ }+ if lease := s.turns[key]; lease != nil && lease.refs > 0 {+ return nil, ErrSessionTurnActive+ }+ if _, held := s.rewinds[key]; held {+ return nil, ErrSessionRewindLocked+ }+ s.rewinds[key] = struct{}{}+ return func() {+ s.mu.Lock()+ delete(s.rewinds, key)+ s.mu.Unlock()+ }, nil+}++// HasRewindLock reports whether rewind currently holds key.+func (s *MemorySessionSandboxBindingStore) HasRewindLock(+ ctx context.Context,+ key SessionSandboxKey,+) (bool, error) {+ if err := key.Validate(); err != nil {+ return false, err+ }+ if err := ctx.Err(); err != nil {+ return false, err+ }+ s.mu.Lock()+ defer s.mu.Unlock()+ _, held := s.rewinds[key]+ return held, nil+}+// TurnState reports whether a chat turn is open and whether its first// resolve may still rebuild a stale sandbox.func (s *MemorySessionSandboxBindingStore) TurnState(diff --git a/internal/sandbox/session_binding_redis.go b/internal/sandbox/session_binding_redis.goindex 6adf4b7a6..8b99e6893 100644--- a/internal/sandbox/session_binding_redis.go+++ b/internal/sandbox/session_binding_redis.go@@ -7,6 +7,7 @@ import ("fmt""strconv""strings"+ "sync""time""unicode"@@ -18,6 +19,8 @@ import (const (redisLifecycleLockLease = 60 * time.SecondredisLifecycleLockRenewInterval = 20 * time.Second+ sessionRewindLockTTL = 2 * time.Minute+ sessionRewindLockRenewInterval = 40 * time.Second)var deleteBindingIfMatchScript = redis.NewScript(`@@ -76,6 +79,9 @@ return 1const sessionTurnLeaseTTL = 30 * time.Minutevar beginTurnScript = redis.NewScript(`+if redis.call('EXISTS', KEYS[2]) == 1 then+ return redis.error_reply('ERR_SESSION_REWIND_LOCKED')+endlocal refs = redis.call('HINCRBY', KEYS[1], 'refs', 1)if refs == 1 thenredis.call('HSET', KEYS[1], 'rebuild', '1')@@ -84,6 +90,18 @@ redis.call('PEXPIRE', KEYS[1], ARGV[1])return refs`)+// KEYS[1] turn lease, KEYS[2] rewind lock. ARGV[1] owner token, ARGV[2] TTL ms.+var tryLockRewindScript = redis.NewScript(`+if redis.call('EXISTS', KEYS[1]) == 1 then+ return redis.error_reply('ERR_SESSION_TURN_ACTIVE')+end+if redis.call('EXISTS', KEYS[2]) == 1 then+ return 0+end+redis.call('SET', KEYS[2], ARGV[1], 'PX', ARGV[2])+return 1+`)+var endTurnScript = redis.NewScript(`if redis.call('EXISTS', KEYS[1]) == 0 then return 0 endlocal refs = redis.call('HINCRBY', KEYS[1], 'refs', -1)@@ -112,6 +130,9 @@ type RedisSessionSandboxBindingStore struct {namespace stringlockLease time.DurationlockRenewInterval time.Duration+ rewindLockTTL time.Duration+ rewindLockRenew time.Duration+ rewindRenewer func(ctx context.Context, key, token string, lease time.Duration) (bool, error)}// NewRedisSessionSandboxBindingStore creates a fail-closed Redis store.@@ -131,6 +152,8 @@ func NewRedisSessionSandboxBindingStore(namespace: namespace,lockLease: redisLifecycleLockLease,lockRenewInterval: redisLifecycleLockRenewInterval,+ rewindLockTTL: sessionRewindLockTTL,+ rewindLockRenew: sessionRewindLockRenewInterval,}, nil}@@ -372,7 +395,10 @@ func (s *RedisSessionSandboxBindingStore) BeginTurn(if ttlMS <= 0 {ttlMS = (30 * time.Minute).Milliseconds()}- if err := beginTurnScript.Run(ctx, s.client, []string{s.turnKey(key)}, ttlMS).Err(); err != nil {+ if err := beginTurnScript.Run(ctx, s.client, []string{s.turnKey(key), s.rewindKey(key)}, ttlMS).Err(); err != nil {+ if isRewindLockedRedisErr(err) {+ return ErrSessionRewindLocked+ }return fmt.Errorf("begin sandbox turn lease: %w", err)}return nil@@ -437,6 +463,139 @@ func (s *RedisSessionSandboxBindingStore) turnKey(key SessionSandboxKey) stringreturn "weknora:sandbox:session:{" + s.hashTag(key) + "}:turn"}+func (s *RedisSessionSandboxBindingStore) rewindKey(key SessionSandboxKey) string {+ return "weknora:sandbox:session:{" + s.hashTag(key) + "}:rewind"+}++// TryLockRewind takes a distributed exclusive rewind lock for key.+// The lock fails if a chat-turn lease already exists, and is renewed until+// the returned unlock runs so a slow reset+cleanup cannot expire it.+func (s *RedisSessionSandboxBindingStore) TryLockRewind(+ ctx context.Context,+ key SessionSandboxKey,+) (func(), error) {+ if err := key.Validate(); err != nil {+ return nil, err+ }+ token, err := redislock.NewToken()+ if err != nil {+ return nil, err+ }+ lease := s.rewindLease()+ ttlMS := lease.Milliseconds()+ if ttlMS <= 0 {+ ttlMS = sessionRewindLockTTL.Milliseconds()+ }+ acquired, err := tryLockRewindScript.Run(+ ctx, s.client, []string{s.turnKey(key), s.rewindKey(key)}, token, ttlMS,+ ).Int64()+ if err != nil {+ if isTurnActiveRedisErr(err) {+ return nil, ErrSessionTurnActive+ }+ return nil, fmt.Errorf("lock session rewind: %w", err)+ }+ if acquired == 0 {+ return nil, ErrSessionRewindLocked+ }++ stop := make(chan struct{})+ done := make(chan struct{})+ go s.renewRewindLock(stop, done, s.rewindKey(key), token, lease)+ var once sync.Once+ return func() {+ once.Do(func() {+ close(stop)+ <-done+ relCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)+ defer cancel()+ _, _ = redislock.Release(relCtx, s.client, s.rewindKey(key), token)+ })+ }, nil+}++// HasRewindLock reports whether rewind currently holds key.+func (s *RedisSessionSandboxBindingStore) HasRewindLock(+ ctx context.Context,+ key SessionSandboxKey,+) (bool, error) {+ if err := key.Validate(); err != nil {+ return false, err+ }+ n, err := s.client.Exists(ctx, s.rewindKey(key)).Result()+ if err != nil {+ return false, fmt.Errorf("read session rewind lock: %w", err)+ }+ return n > 0, nil+}++func isRewindLockedRedisErr(err error) bool {+ return err != nil && strings.Contains(err.Error(), "ERR_SESSION_REWIND_LOCKED")+}++func isTurnActiveRedisErr(err error) bool {+ return err != nil && strings.Contains(err.Error(), "ERR_SESSION_TURN_ACTIVE")+}++func (s *RedisSessionSandboxBindingStore) rewindLease() time.Duration {+ if s != nil && s.rewindLockTTL > 0 {+ return s.rewindLockTTL+ }+ return sessionRewindLockTTL+}++func (s *RedisSessionSandboxBindingStore) rewindRenewInterval() time.Duration {+ if s != nil && s.rewindLockRenew > 0 {+ return s.rewindLockRenew+ }+ return sessionRewindLockRenewInterval+}++func (s *RedisSessionSandboxBindingStore) renewRewind(+ ctx context.Context, key, token string, lease time.Duration,+) (bool, error) {+ if s != nil && s.rewindRenewer != nil {+ return s.rewindRenewer(ctx, key, token, lease)+ }+ return redislock.Renew(ctx, s.client, key, token, lease)+}++func (s *RedisSessionSandboxBindingStore) renewRewindLock(+ stop <-chan struct{}, done chan<- struct{}, key, token string, lease time.Duration,+) {+ defer close(done)+ interval := s.rewindRenewInterval()+ if interval <= 0 || interval >= lease {+ interval = lease / 3+ }+ if interval <= 0 {+ return+ }+ ticker := time.NewTicker(interval)+ defer ticker.Stop()+ for {+ select {+ case <-stop:+ return+ case <-ticker.C:+ renewed, err := s.renewRewind(context.Background(), key, token, lease)+ if err == nil && renewed {+ continue+ }+ // A blip talking to Redis, or a lost lease, must not kill the+ // renew loop: git reset can still be running, and the 2m TTL+ // would otherwise expire under it. Re-acquire on both, so the+ // original unlock token still matches a key that vanished — an+ // errored renew is exactly the case where the key may have+ // expired underneath us, and sitting the tick out is what lets+ // a short outage hand the session to a second rewind.+ _, _ = redislock.TryAcquire(+ context.Background(), s.client, key, token, lease,+ )+ }+ }+}+func (s *RedisSessionSandboxBindingStore) bindingKey(key SessionSandboxKey) string {return "weknora:sandbox:session:{" + s.hashTag(key) + "}:binding"}diff --git a/internal/sandbox/session_binding_redis_test.go b/internal/sandbox/session_binding_redis_test.goindex f6ff14835..5b968bbe1 100644--- a/internal/sandbox/session_binding_redis_test.go+++ b/internal/sandbox/session_binding_redis_test.go@@ -3,9 +3,12 @@ package sandboximport ("context""encoding/json"+ "errors"+ "sync/atomic""testing""time"+ "github.com/Tencent/WeKnora/internal/common/redislock""github.com/alicebob/miniredis/v2""github.com/redis/go-redis/v9""github.com/stretchr/testify/require"@@ -61,6 +64,80 @@ func TestRedisSessionSandboxBindingStoreTurnLease(t *testing.T) {require.Zero(t, exists, "consuming a missing turn must not create a lease key")}+func TestRedisSessionSandboxBindingStoreBeginTurnFailsWhenRewindLocked(t *testing.T) {+ store, _, _ := newRedisBindingTestStore(t)+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-turn"}++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ held, err := store.HasRewindLock(ctx, key)+ require.NoError(t, err)+ require.True(t, held)+ require.ErrorIs(t, store.BeginTurn(ctx, key), ErrSessionRewindLocked)+ unlock()++ require.NoError(t, store.BeginTurn(ctx, key))+ require.NoError(t, store.EndTurn(ctx, key))+}++func TestRedisSessionSandboxBindingStoreTryLockRewindFailsWhenTurnActive(t *testing.T) {+ store, _, _ := newRedisBindingTestStore(t)+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-turn-rewind"}++ require.NoError(t, store.BeginTurn(ctx, key))+ _, err := store.TryLockRewind(ctx, key)+ require.ErrorIs(t, err, ErrSessionTurnActive)+ require.NoError(t, store.EndTurn(ctx, key))++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ unlock()+}++func TestRedisSessionSandboxBindingStoreRewindLockRenews(t *testing.T) {+ store, client, _ := newRedisBindingTestStore(t)+ store.rewindLockTTL = 150 * time.Millisecond+ store.rewindLockRenew = 40 * time.Millisecond+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-renew"}++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ t.Cleanup(unlock)++ time.Sleep(220 * time.Millisecond)+ n, err := client.Exists(ctx, store.rewindKey(key)).Result()+ require.NoError(t, err)+ require.Equal(t, int64(1), n, "rewind lock must be renewed past the original TTL")+}++func TestRedisSessionSandboxBindingStoreRewindLockRenewSurvivesErrors(t *testing.T) {+ store, client, _ := newRedisBindingTestStore(t)+ store.rewindLockTTL = 150 * time.Millisecond+ store.rewindLockRenew = 40 * time.Millisecond+ var fails atomic.Int32+ store.rewindRenewer = func(ctx context.Context, key, token string, lease time.Duration) (bool, error) {+ if fails.Add(1) == 1 {+ return false, errors.New("redis blip")+ }+ return redislock.Renew(ctx, store.client, key, token, lease)+ }+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-renew-blip"}++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ t.Cleanup(unlock)++ time.Sleep(220 * time.Millisecond)+ n, err := client.Exists(ctx, store.rewindKey(key)).Result()+ require.NoError(t, err)+ require.Equal(t, int64(1), n, "rewind lock renew must keep retrying after a transient error")+ require.GreaterOrEqual(t, fails.Load(), int32(2))+}+func TestRedisSessionSandboxBindingStoreInvalidatesByConfig(t *testing.T) {store, _, _ := newRedisBindingTestStore(t)testSessionSandboxBindingInvalidateByConfig(t, store)diff --git a/internal/sandbox/session_binding_test.go b/internal/sandbox/session_binding_test.goindex 2e2e13938..d88b7c0e6 100644--- a/internal/sandbox/session_binding_test.go+++ b/internal/sandbox/session_binding_test.go@@ -336,6 +336,57 @@ func testSessionTurnLeaseStore(t *testing.T, store sessionTurnLeaseStore) {require.Error(t, store.BeginTurn(cancelled, key))}+func TestMemorySessionSandboxBindingStoreRewindLock(t *testing.T) {+ t.Parallel()+ store := NewMemorySessionSandboxBindingStore()+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind"}++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ _, err = store.TryLockRewind(ctx, key)+ require.ErrorIs(t, err, ErrSessionRewindLocked)+ unlock()++ unlock, err = store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ unlock()+}++func TestMemorySessionSandboxBindingStoreBeginTurnFailsWhenRewindLocked(t *testing.T) {+ t.Parallel()+ store := NewMemorySessionSandboxBindingStore()+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-rewind-turn"}++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ held, err := store.HasRewindLock(ctx, key)+ require.NoError(t, err)+ require.True(t, held)+ require.ErrorIs(t, store.BeginTurn(ctx, key), ErrSessionRewindLocked)+ unlock()++ require.NoError(t, store.BeginTurn(ctx, key))+ require.NoError(t, store.EndTurn(ctx, key))+}++func TestMemorySessionSandboxBindingStoreTryLockRewindFailsWhenTurnActive(t *testing.T) {+ t.Parallel()+ store := NewMemorySessionSandboxBindingStore()+ ctx := context.Background()+ key := SessionSandboxKey{TenantID: 42, SessionID: "session-turn-rewind"}++ require.NoError(t, store.BeginTurn(ctx, key))+ _, err := store.TryLockRewind(ctx, key)+ require.ErrorIs(t, err, ErrSessionTurnActive)+ require.NoError(t, store.EndTurn(ctx, key))++ unlock, err := store.TryLockRewind(ctx, key)+ require.NoError(t, err)+ unlock()+}+func TestMemorySessionSandboxBindingStoreSeparatesTenants(t *testing.T) {t.Parallel()testSessionSandboxBindingTenantIsolation(t, NewMemorySessionSandboxBindingStore())diff --git a/internal/sandbox/session_manager.go b/internal/sandbox/session_manager.goindex 46ef7c715..b23f41da2 100644--- a/internal/sandbox/session_manager.go+++ b/internal/sandbox/session_manager.go@@ -59,6 +59,18 @@ const sessionInputEnvVar = "WEKNORA_SESSION_INPUT_DIR"// shell_exec work_dir must stay underneath this path.const SessionWorkspaceRoot = "/workspace"+// SessionGitDir is the git metadata directory for per-turn workspace+// checkpoints. It lives on the sandbox root filesystem so a fork snapshot+// still copies the object store, but outside SessionWorkspaceRoot so+// `rm -rf /workspace` (or an agent cleaning the work tree) cannot drop+// checkpoint history that rewind and fork later reset to.+//+// Checkpoints used to live in SessionWorkspaceRoot/.git, and sandboxes+// provisioned before this constant existed still hold theirs there. The+// shared git preamble adopts that repository on first use so SHAs recorded+// before the move keep resolving; see gitWorkspaceAdoptLegacyRepo.+const SessionGitDir = "/var/lib/weknora/workspace.git"+// sessionArtifactDirBootstrapTimeout bounds directory creation and access// checks, performed with the execution identity.const sessionArtifactDirBootstrapTimeout = 15 * time.Second@@ -1122,6 +1134,45 @@ func (m *SessionBoundManager) HasActiveTurn(ctx context.Context, sessionID strinreturn active, err}+// TryLockRewind takes an exclusive rewind lock for sessionID. Stores that do+// not implement rewind locking succeed as a no-op so local tests without a+// lease store still rewind.+func (m *SessionBoundManager) TryLockRewind(ctx context.Context, sessionID string) (func(), error) {+ noop := func() {}+ if m == nil {+ return noop, nil+ }+ locker, ok := m.bindings.(interface {+ TryLockRewind(context.Context, SessionSandboxKey) (func(), error)+ })+ if !ok {+ return noop, nil+ }+ key, err := m.sessionKey(ctx, sessionID)+ if err != nil {+ return nil, err+ }+ return locker.TryLockRewind(ctx, key)+}++// HasRewindLock reports whether rewind currently holds sessionID.+func (m *SessionBoundManager) HasRewindLock(ctx context.Context, sessionID string) (bool, error) {+ if m == nil {+ return false, nil+ }+ reader, ok := m.bindings.(interface {+ HasRewindLock(context.Context, SessionSandboxKey) (bool, error)+ })+ if !ok {+ return false, nil+ }+ key, err := m.sessionKey(ctx, sessionID)+ if err != nil {+ return false, err+ }+ return reader.HasRewindLock(ctx, key)+}+// CreateForkSnapshot snapshots the session's already-bound sandbox. It never// provisions: an unbound session or a backend without snapshots returns an// error so fork can degrade.diff --git a/internal/sandbox/session_manager_test.go b/internal/sandbox/session_manager_test.goindex 46dfcda74..1f044b2e5 100644--- a/internal/sandbox/session_manager_test.go+++ b/internal/sandbox/session_manager_test.go@@ -624,6 +624,74 @@ func TestHasActiveTurnReportsLeaseState(t *testing.T) {require.True(t, busy)}+func TestTryLockRewindIsExclusive(t *testing.T) {+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))+ store := NewMemorySessionSandboxBindingStore()+ cfg := DefaultConfig()+ cfg.CubeTemplate = "tpl-test"+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{+ Config: cfg,+ Client: newFakeRemoteClient(SandboxTypeCube),+ Store: store,+ Checker: &fakeSessionExistenceChecker{exists: true},+ SkipHealthProbe: true,+ })+ require.NoError(t, err)++ unlock, err := mgr.TryLockRewind(ctx, "sess-1")+ require.NoError(t, err)+ _, err = mgr.TryLockRewind(ctx, "sess-1")+ require.ErrorIs(t, err, ErrSessionRewindLocked)+ unlock()+}++func TestBeginSessionTurnFailsWhenRewindLocked(t *testing.T) {+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))+ store := NewMemorySessionSandboxBindingStore()+ cfg := DefaultConfig()+ cfg.CubeTemplate = "tpl-test"+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{+ Config: cfg,+ Client: newFakeRemoteClient(SandboxTypeCube),+ Store: store,+ Checker: &fakeSessionExistenceChecker{exists: true},+ SkipHealthProbe: true,+ })+ require.NoError(t, err)++ unlock, err := mgr.TryLockRewind(ctx, "sess-1")+ require.NoError(t, err)+ held, err := mgr.HasRewindLock(ctx, "sess-1")+ require.NoError(t, err)+ require.True(t, held)+ require.ErrorIs(t, mgr.BeginSessionTurn(ctx, "sess-1"), ErrSessionRewindLocked)+ unlock()+ require.NoError(t, mgr.BeginSessionTurn(ctx, "sess-1"))+}++func TestTryLockRewindFailsWhenTurnActive(t *testing.T) {+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))+ store := NewMemorySessionSandboxBindingStore()+ cfg := DefaultConfig()+ cfg.CubeTemplate = "tpl-test"+ mgr, err := NewSessionBoundManager(SessionBoundManagerConfig{+ Config: cfg,+ Client: newFakeRemoteClient(SandboxTypeCube),+ Store: store,+ Checker: &fakeSessionExistenceChecker{exists: true},+ SkipHealthProbe: true,+ })+ require.NoError(t, err)++ require.NoError(t, mgr.BeginSessionTurn(ctx, "sess-1"))+ _, err = mgr.TryLockRewind(ctx, "sess-1")+ require.ErrorIs(t, err, ErrSessionTurnActive)+ require.NoError(t, mgr.EndSessionTurn(ctx, "sess-1"))+ unlock, err := mgr.TryLockRewind(ctx, "sess-1")+ require.NoError(t, err)+ unlock()+}+func TestHasActiveTurnWithoutLeaseStoreIsNotBusy(t *testing.T) {ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(10000))store := leaseFreeBindingStore{SessionSandboxBindingStore: NewMemorySessionSandboxBindingStore()}diff --git a/internal/stream/memory_manager.go b/internal/stream/memory_manager.goindex 5c79cab70..3f1be193d 100644--- a/internal/stream/memory_manager.go+++ b/internal/stream/memory_manager.go@@ -299,5 +299,30 @@ func (m *MemoryStreamManager) ClearLiveRun(return nil}+// DropMessageStreams removes event and steer buffers for deleted messages so a+// later rewind cannot replay or steer a turn that no longer exists.+func (m *MemoryStreamManager) DropMessageStreams(+ _ context.Context, sessionID string, messageIDs []string,+) error {+ if sessionID == "" || len(messageIDs) == 0 {+ return nil+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ sessionMap := m.streams[sessionID]+ for _, messageID := range messageIDs {+ if sessionMap != nil {+ delete(sessionMap, messageID)+ }+ if marker, ok := m.liveRuns[sessionID]; ok && marker.assistantMessageID == messageID {+ delete(m.liveRuns, sessionID)+ }+ }+ if sessionMap != nil && len(sessionMap) == 0 {+ delete(m.streams, sessionID)+ }+ return nil+}+// Ensure MemoryStreamManager implements StreamManager interfacevar _ interfaces.StreamManager = (*MemoryStreamManager)(nil)diff --git a/internal/stream/redis_live_run_test.go b/internal/stream/redis_live_run_test.goindex 21ade7d19..b5285b851 100644--- a/internal/stream/redis_live_run_test.go+++ b/internal/stream/redis_live_run_test.go@@ -182,3 +182,43 @@ func TestAppendSteerEventsDeduplicatesClientIDs(t *testing.T) {})}}++func TestDropMessageStreamsRemovesEventsSteerAndLiveRun(t *testing.T) {+ mgr := NewMemoryStreamManager()+ ctx := context.Background()+ require.NoError(t, mgr.AppendEvent(ctx, "sess", "a-1", interfaces.StreamEvent{ID: "e1"}))+ require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "a-1", []interfaces.StreamEvent{{ID: "s1"}}))+ require.NoError(t, mgr.SetLiveRun(ctx, "sess", "a-1", "req"))++ require.NoError(t, mgr.DropMessageStreams(ctx, "sess", []string{"a-1"}))++ events, _, err := mgr.GetEvents(ctx, "sess", "a-1", 0)+ require.NoError(t, err)+ require.Empty(t, events)+ steer, _, err := mgr.GetSteerEvents(ctx, "sess", "a-1", 0)+ require.NoError(t, err)+ require.Empty(t, steer)+ liveID, _, err := mgr.GetLiveRun(ctx, "sess")+ require.NoError(t, err)+ require.Empty(t, liveID)+}++func TestRedisDropMessageStreamsRemovesEventsSteerAndLiveRun(t *testing.T) {+ mgr, _ := newTestRedisStreamManager(t, time.Hour)+ ctx := context.Background()+ require.NoError(t, mgr.AppendEvent(ctx, "sess", "a-1", interfaces.StreamEvent{ID: "e1"}))+ require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "a-1", []interfaces.StreamEvent{{ID: "s1"}}))+ require.NoError(t, mgr.SetLiveRun(ctx, "sess", "a-1", "req"))++ require.NoError(t, mgr.DropMessageStreams(ctx, "sess", []string{"a-1"}))++ events, _, err := mgr.GetEvents(ctx, "sess", "a-1", 0)+ require.NoError(t, err)+ require.Empty(t, events)+ steer, _, err := mgr.GetSteerEvents(ctx, "sess", "a-1", 0)+ require.NoError(t, err)+ require.Empty(t, steer)+ liveID, _, err := mgr.GetLiveRun(ctx, "sess")+ require.NoError(t, err)+ require.Empty(t, liveID)+}diff --git a/internal/stream/redis_manager.go b/internal/stream/redis_manager.goindex f40d21d15..4e0191ac4 100644--- a/internal/stream/redis_manager.go+++ b/internal/stream/redis_manager.go@@ -496,6 +496,40 @@ func (r *RedisStreamManager) ClearLiveRun(return nil}+// DropMessageStreams removes event and steer lists for deleted messages, and+// clears a live-run marker that still names one of them.+func (r *RedisStreamManager) DropMessageStreams(+ ctx context.Context, sessionID string, messageIDs []string,+) error {+ if sessionID == "" || len(messageIDs) == 0 {+ return nil+ }+ keys := make([]string, 0, len(messageIDs)*2+1)+ wantLive := make(map[string]struct{}, len(messageIDs))+ for _, messageID := range messageIDs {+ if messageID == "" {+ continue+ }+ wantLive[messageID] = struct{}{}+ keys = append(keys, r.buildKey(sessionID, messageID), r.buildSteerKey(sessionID, messageID))+ }+ if len(keys) > 0 {+ if err := r.client.Del(ctx, keys...).Err(); err != nil {+ return fmt.Errorf("failed to drop message streams in Redis: %w", err)+ }+ }+ liveID, _, err := r.GetLiveRun(ctx, sessionID)+ if err != nil {+ return err+ }+ if _, ok := wantLive[liveID]; ok {+ if err := r.ClearLiveRun(ctx, sessionID, liveID); err != nil {+ return err+ }+ }+ return nil+}+// Close closes the Redis connectionfunc (r *RedisStreamManager) Close() error {return r.client.Close()diff --git a/internal/types/interfaces/message.go b/internal/types/interfaces/message.goindex 31159fc3e..c7d11a004 100644--- a/internal/types/interfaces/message.go+++ b/internal/types/interfaces/message.go@@ -131,6 +131,13 @@ type MessageRepository interface {GetLatestContextCheckpoint(ctx context.Context, sessionID string) (*types.Message, error)// DeleteMessage deletes a messageDeleteMessage(ctx context.Context, sessionID string, id string) error+ // DeleteMessagesFrom deletes every message at or after the+ // (boundary, boundaryID) composite cursor and returns the deleted rows,+ // oldest first. inclusive keeps or drops the boundary message itself,+ // which is what separates a user rewind point from an assistant one.+ DeleteMessagesFrom(+ ctx context.Context, sessionID string, boundary time.Time, boundaryID string, inclusive bool,+ ) ([]*types.Message, error)// DeleteMessagesBySessionID deletes all messages belonging to a sessionDeleteMessagesBySessionID(ctx context.Context, sessionID string) error// GetFirstMessageOfUser gets the first message of a userdiff --git a/internal/types/qa_request.go b/internal/types/qa_request.goindex e626dab91..bb8b2655b 100644--- a/internal/types/qa_request.go+++ b/internal/types/qa_request.go@@ -76,4 +76,10 @@ type QARequest struct {// persists accepted ones through this sink. A structural interface so// neither package imports the other; handler-owned, nil for IM/embed.SteerSink SteerSink+ // TurnLeaseHeld reports that the caller already took the session's+ // send-side turn lease (and already rejected the send if a rewind holds+ // the session) before persisting this turn's messages. HTTP send does;+ // IM/MCP, which call the QA services directly, do not and leave this+ // false so the service takes the lease itself.+ TurnLeaseHeld bool}