WeKnora/internal/application/service/workspace_checkpointer.go

173 lines
6.3 KiB
Go
Raw Normal View History

feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
// Package service - per-turn /workspace git checkpoints.
//
// WorkspaceCheckpointer commits the session sandbox's /workspace at the end of
feat(session): in-place rewind with workspace checkpoint reset (#3469) * refactor(session): extract shared workspace git reset helper Fork bootstrap and in-place rewind both need the same /workspace reset script. Move it out of fork_bootstrapper so rewind can reuse it without copying ExecShellCommand plumbing. * feat(message): add DeleteMessagesFrom for rewind truncation Rewind needs a composite created_at+id cursor so same-millisecond messages after the fork point are not left behind. Delete inside a transaction and return the rows so callers can log the count. * feat(session): add in-place rewind service Truncate the current session at a user or assistant message and git-reset the live sandbox when a reachable checkpoint exists. Reset failure is fail-closed so messages are never deleted ahead of the workspace. * feat(session): expose POST /sessions/:id/rewind Wire SessionRewindService through the session handler and container so the client can rewind in place. Busy sources map to 409; git reset failures stay 500. * feat(chat): add rewind API client and i18n copy Expose rewindSession with the same 180s timeout as fork, and add chat.rewind strings in all five locales so the confirm dialog is not hardcoded Chinese. * feat(chat): add rewind button with confirm dialog Offer in-place rewind next to fork on user and assistant messages. Confirm before truncating the thread, then reset locally and prefill the original question when the cut point is a user message. * fix(chat): confirm rewind with a compact popover Replace the full-page confirm dialog with a small popconfirm above the rewind button, and shorten the swagger description to satisfy line length. * fix(chat): skip markdown images with an empty destination Empty ![]() was rendered as <img src="">, which shows as a broken image in the reply. * fix(chat): clip sandbox panel slide-in and rename open tooltip Keep the enter animation inside the viewport so it cannot flash a document scrollbar and jump the page. Rename the header toggle from sandbox terminal to expand sidebar. * fix(session): 回滚时完成截断、互斥发送并重拉历史 客户端中断不再让 git reset 成功后留下未删的消息;reset/删消息前复查 busy,并锁住当前会话输入。成功后重拉历史,避免切会话预填串台和 steer 分段截错。 * fix(session): 工作区 git 外置,并让未开箱 fork 的回滚对齐 SHA checkpoint、回滚和 fork 共用 --git-dir=/var/lib/weknora/workspace.git,避免 rm -rf /workspace 丢掉历史。 未开箱分叉会话回滚时改写或清除 ForkBootstrap,避免第一次开箱仍 reset 到旧切点。 * fix(session): 回滚加会话锁,并堵住发送中回滚与脏 SHA 同一会话并发回滚互斥(进程内 + Redis),冲突返回 409。发送/流式中禁用回滚按钮;历史重拉成功后再改界面。未开箱 fork 的 checkpoint SHA 必须是 40 位 hex。工作区 git 只认外置 GIT_DIR,不再 mv/rm 根上的 .git。 * fix(session): 未开箱 fork 回滚成功时不要提示没有沙箱 ForkBootstrap 已对齐切点后返回 workspace_reset,前端走「已回滚」;清掉引导时改报 NO_CHECKPOINT。纯聊天仍用 NO_SANDBOX。 * fix(chat): stub composerLocked in steer interaction tests handleSteerMsg now bails when rewind locks the composer. The VM harness did not provide that ref, so CI threw ReferenceError on every steer case. * fix(session): allow git-layout mkdir in pinned checkpoint test SkipWorkspacePrep still omits the input/output bootstrap exec. The checkpoint script now mkdirs WORK_TREE and GIT_DIR, so the old "command must not contain mkdir" assertion was stale. * fix(session): block send while rewind holds the session lock BeginTurn now fails if the rewind key is held, so AgentQA cannot start during git reset. Knowledge-chat and executeQA check the same lock before persisting messages. composerLocked is still page-local. * fix(session): close send/rewind races and fail closed without a checkpoint Hold the turn lease before persist so rewind cannot truncate an in-flight send. TryLockRewind fails while a turn is live; emptying the conversation resets the workspace through the same git path as a SHA rewind. * fix(session): wrap rewind reset call to satisfy line length lint * fix(session): fail closed on a replaced sandbox and close leftover rewind holes Do not truncate history when the live workspace cannot follow the checkpoint, retry deletes after a successful git reset, and keep send and rewind exclusive even without a sandbox manager. * fix(session): address rewind review findings Correctness: - Adopt a pre-move /workspace/.git into SessionGitDir on first use. Sandboxes provisioned before the git dir moved out of the work tree still hold their checkpoints there, so every SHA recorded on those turns stopped resolving: rewind 500'd instead of truncating and fork's rollback failed on a bad object. Adoption is guarded on the new dir being absent and on the work-tree repo carrying the checkpointer's committer identity, so an agent's own `git init` in /workspace is left alone. - Only fail a send closed when BeginSessionTurn reports a rewind lock. Every other lease error degrades to running without a lease, as before rewind existed; a Redis blip on the lease script was rejecting the user's message. - Release an abandoned fork snapshot after the truncate lands, not before. Clearing the bootstrap column is a DB write a retry can redo; deleting the snapshot is not, and a delete that exhausted its retries left the fork with no workspace to boot from under a full transcript. - Re-acquire the rewind lock when a renew call errors, not just when it reports the lease lost. Sitting the tick out let a short Redis outage expire the 2m key mid-reset and hand the session to a second rewind. - Keep the history cursor when a post-rewind reload fails. Clearing it sent the next scroll-up back to the newest page, which the kept prefix already holds, instead of to older messages. Efficiency: - Add ListAssistantCheckpointsUpTo and use it to answer "which checkpoint does kept history still reach". Rewind was reading every message body and artifact row in the session to find one SHA. - Take the send-side turn lease once per request. The handler already holds it before persisting; QARequest.TurnLeaseHeld lets the QA services skip their own, so IM/MCP still take one and HTTP send stops doubling every rewind check and lease round trip. - Batch the suggestion delete behind DeleteByMessageIDs instead of one query per deleted message while the rewind lock is held. - Resolve the rewind affordance for the whole transcript in one pass rather than two list scans per rendered row on every streamed token. Cleanup: - Drop the SANDBOX_REPLACED skip reason, which the service never produces (it fail-closes with a 409), along with its copy in all five locales. - Drop GetMessagesBySession from rewindMessageStore; rewind never calls it. - Drop the unused chat.rewind.confirmTitle copy from all five locales. - Restore the chatHeader.toggleSandboxPanel wording this branch had changed unrelated to rewind. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-20 13:01:00 +00:00
// 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.
feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
//
// Contract:
// - Never returns an error. A failed checkpoint yields nil, the message
// simply carries no checkpoint, and that fork point degrades.
// - Never lazy-creates a sandbox: an empty sandboxID short-circuits.
// - Idempotent inside the sandbox: the script initialises the repository
// only when absent, so pause/resume and sandbox rebuilds self-heal.
package service
import (
"context"
"fmt"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
)
// SandboxShellRunner is the narrow subset of sandbox behaviour the
// checkpointer needs. *sandbox.SessionBoundManager satisfies it in production;
// tests use a fake to assert on the emitted script without a real sandbox.
type SandboxShellRunner interface {
ExecShellCommand(
ctx context.Context,
sessionID, command, workDir string,
timeout time.Duration,
env map[string]string,
) (*sandbox.ExecuteResult, error)
}
// workspaceCheckpointTimeout bounds the git round-trip. `git add -A` walks the
// whole working tree, so this is generous relative to a normal commit but
// still short enough that a wedged sandbox cannot stall the completion path.
const workspaceCheckpointTimeout = 30 * time.Second
// gitSHAPattern matches a full 40-character hex object name. The script's last
// stdout line must look like one; anything else means git printed a warning or
// the script diverged, and we refuse to record a checkpoint we cannot trust.
var gitSHAPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
// WorkspaceCheckpointer commits /workspace after each agent turn.
type WorkspaceCheckpointer struct {
runner SandboxShellRunner
}
// NewWorkspaceCheckpointer wires a checkpointer. A nil runner yields a
// checkpointer that degrades to "no checkpoint", matching the graceful
// degradation contract used by ArtifactCollector.
func NewWorkspaceCheckpointer(runner SandboxShellRunner) *WorkspaceCheckpointer {
return &WorkspaceCheckpointer{runner: runner}
}
// checkpointScript renders the idempotent init-and-commit script.
//
// Ordering matters in two places:
//
feat(session): in-place rewind with workspace checkpoint reset (#3469) * refactor(session): extract shared workspace git reset helper Fork bootstrap and in-place rewind both need the same /workspace reset script. Move it out of fork_bootstrapper so rewind can reuse it without copying ExecShellCommand plumbing. * feat(message): add DeleteMessagesFrom for rewind truncation Rewind needs a composite created_at+id cursor so same-millisecond messages after the fork point are not left behind. Delete inside a transaction and return the rows so callers can log the count. * feat(session): add in-place rewind service Truncate the current session at a user or assistant message and git-reset the live sandbox when a reachable checkpoint exists. Reset failure is fail-closed so messages are never deleted ahead of the workspace. * feat(session): expose POST /sessions/:id/rewind Wire SessionRewindService through the session handler and container so the client can rewind in place. Busy sources map to 409; git reset failures stay 500. * feat(chat): add rewind API client and i18n copy Expose rewindSession with the same 180s timeout as fork, and add chat.rewind strings in all five locales so the confirm dialog is not hardcoded Chinese. * feat(chat): add rewind button with confirm dialog Offer in-place rewind next to fork on user and assistant messages. Confirm before truncating the thread, then reset locally and prefill the original question when the cut point is a user message. * fix(chat): confirm rewind with a compact popover Replace the full-page confirm dialog with a small popconfirm above the rewind button, and shorten the swagger description to satisfy line length. * fix(chat): skip markdown images with an empty destination Empty ![]() was rendered as <img src="">, which shows as a broken image in the reply. * fix(chat): clip sandbox panel slide-in and rename open tooltip Keep the enter animation inside the viewport so it cannot flash a document scrollbar and jump the page. Rename the header toggle from sandbox terminal to expand sidebar. * fix(session): 回滚时完成截断、互斥发送并重拉历史 客户端中断不再让 git reset 成功后留下未删的消息;reset/删消息前复查 busy,并锁住当前会话输入。成功后重拉历史,避免切会话预填串台和 steer 分段截错。 * fix(session): 工作区 git 外置,并让未开箱 fork 的回滚对齐 SHA checkpoint、回滚和 fork 共用 --git-dir=/var/lib/weknora/workspace.git,避免 rm -rf /workspace 丢掉历史。 未开箱分叉会话回滚时改写或清除 ForkBootstrap,避免第一次开箱仍 reset 到旧切点。 * fix(session): 回滚加会话锁,并堵住发送中回滚与脏 SHA 同一会话并发回滚互斥(进程内 + Redis),冲突返回 409。发送/流式中禁用回滚按钮;历史重拉成功后再改界面。未开箱 fork 的 checkpoint SHA 必须是 40 位 hex。工作区 git 只认外置 GIT_DIR,不再 mv/rm 根上的 .git。 * fix(session): 未开箱 fork 回滚成功时不要提示没有沙箱 ForkBootstrap 已对齐切点后返回 workspace_reset,前端走「已回滚」;清掉引导时改报 NO_CHECKPOINT。纯聊天仍用 NO_SANDBOX。 * fix(chat): stub composerLocked in steer interaction tests handleSteerMsg now bails when rewind locks the composer. The VM harness did not provide that ref, so CI threw ReferenceError on every steer case. * fix(session): allow git-layout mkdir in pinned checkpoint test SkipWorkspacePrep still omits the input/output bootstrap exec. The checkpoint script now mkdirs WORK_TREE and GIT_DIR, so the old "command must not contain mkdir" assertion was stale. * fix(session): block send while rewind holds the session lock BeginTurn now fails if the rewind key is held, so AgentQA cannot start during git reset. Knowledge-chat and executeQA check the same lock before persisting messages. composerLocked is still page-local. * fix(session): close send/rewind races and fail closed without a checkpoint Hold the turn lease before persist so rewind cannot truncate an in-flight send. TryLockRewind fails while a turn is live; emptying the conversation resets the workspace through the same git path as a SHA rewind. * fix(session): wrap rewind reset call to satisfy line length lint * fix(session): fail closed on a replaced sandbox and close leftover rewind holes Do not truncate history when the live workspace cannot follow the checkpoint, retry deletes after a successful git reset, and keep send and rewind exclusive even without a sandbox manager. * fix(session): address rewind review findings Correctness: - Adopt a pre-move /workspace/.git into SessionGitDir on first use. Sandboxes provisioned before the git dir moved out of the work tree still hold their checkpoints there, so every SHA recorded on those turns stopped resolving: rewind 500'd instead of truncating and fork's rollback failed on a bad object. Adoption is guarded on the new dir being absent and on the work-tree repo carrying the checkpointer's committer identity, so an agent's own `git init` in /workspace is left alone. - Only fail a send closed when BeginSessionTurn reports a rewind lock. Every other lease error degrades to running without a lease, as before rewind existed; a Redis blip on the lease script was rejecting the user's message. - Release an abandoned fork snapshot after the truncate lands, not before. Clearing the bootstrap column is a DB write a retry can redo; deleting the snapshot is not, and a delete that exhausted its retries left the fork with no workspace to boot from under a full transcript. - Re-acquire the rewind lock when a renew call errors, not just when it reports the lease lost. Sitting the tick out let a short Redis outage expire the 2m key mid-reset and hand the session to a second rewind. - Keep the history cursor when a post-rewind reload fails. Clearing it sent the next scroll-up back to the newest page, which the kept prefix already holds, instead of to older messages. Efficiency: - Add ListAssistantCheckpointsUpTo and use it to answer "which checkpoint does kept history still reach". Rewind was reading every message body and artifact row in the session to find one SHA. - Take the send-side turn lease once per request. The handler already holds it before persisting; QARequest.TurnLeaseHeld lets the QA services skip their own, so IM/MCP still take one and HTTP send stops doubling every rewind check and lease round trip. - Batch the suggestion delete behind DeleteByMessageIDs instead of one query per deleted message while the rewind lock is held. - Resolve the rewind affordance for the whole transcript in one pass rather than two list scans per rendered row on every streamed token. Cleanup: - Drop the SANDBOX_REPLACED skip reason, which the service never produces (it fail-closes with a 409), along with its copy in all five locales. - Drop GetMessagesBySession from rewindMessageStore; rewind never calls it. - Drop the unused chat.rewind.confirmTitle copy from all five locales. - Restore the chatHeader.toggleSandboxPanel wording this branch had changed unrelated to rewind. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-20 13:01:00 +00:00
// - `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.
feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
//
// - `--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.
feat(session): in-place rewind with workspace checkpoint reset (#3469) * refactor(session): extract shared workspace git reset helper Fork bootstrap and in-place rewind both need the same /workspace reset script. Move it out of fork_bootstrapper so rewind can reuse it without copying ExecShellCommand plumbing. * feat(message): add DeleteMessagesFrom for rewind truncation Rewind needs a composite created_at+id cursor so same-millisecond messages after the fork point are not left behind. Delete inside a transaction and return the rows so callers can log the count. * feat(session): add in-place rewind service Truncate the current session at a user or assistant message and git-reset the live sandbox when a reachable checkpoint exists. Reset failure is fail-closed so messages are never deleted ahead of the workspace. * feat(session): expose POST /sessions/:id/rewind Wire SessionRewindService through the session handler and container so the client can rewind in place. Busy sources map to 409; git reset failures stay 500. * feat(chat): add rewind API client and i18n copy Expose rewindSession with the same 180s timeout as fork, and add chat.rewind strings in all five locales so the confirm dialog is not hardcoded Chinese. * feat(chat): add rewind button with confirm dialog Offer in-place rewind next to fork on user and assistant messages. Confirm before truncating the thread, then reset locally and prefill the original question when the cut point is a user message. * fix(chat): confirm rewind with a compact popover Replace the full-page confirm dialog with a small popconfirm above the rewind button, and shorten the swagger description to satisfy line length. * fix(chat): skip markdown images with an empty destination Empty ![]() was rendered as <img src="">, which shows as a broken image in the reply. * fix(chat): clip sandbox panel slide-in and rename open tooltip Keep the enter animation inside the viewport so it cannot flash a document scrollbar and jump the page. Rename the header toggle from sandbox terminal to expand sidebar. * fix(session): 回滚时完成截断、互斥发送并重拉历史 客户端中断不再让 git reset 成功后留下未删的消息;reset/删消息前复查 busy,并锁住当前会话输入。成功后重拉历史,避免切会话预填串台和 steer 分段截错。 * fix(session): 工作区 git 外置,并让未开箱 fork 的回滚对齐 SHA checkpoint、回滚和 fork 共用 --git-dir=/var/lib/weknora/workspace.git,避免 rm -rf /workspace 丢掉历史。 未开箱分叉会话回滚时改写或清除 ForkBootstrap,避免第一次开箱仍 reset 到旧切点。 * fix(session): 回滚加会话锁,并堵住发送中回滚与脏 SHA 同一会话并发回滚互斥(进程内 + Redis),冲突返回 409。发送/流式中禁用回滚按钮;历史重拉成功后再改界面。未开箱 fork 的 checkpoint SHA 必须是 40 位 hex。工作区 git 只认外置 GIT_DIR,不再 mv/rm 根上的 .git。 * fix(session): 未开箱 fork 回滚成功时不要提示没有沙箱 ForkBootstrap 已对齐切点后返回 workspace_reset,前端走「已回滚」;清掉引导时改报 NO_CHECKPOINT。纯聊天仍用 NO_SANDBOX。 * fix(chat): stub composerLocked in steer interaction tests handleSteerMsg now bails when rewind locks the composer. The VM harness did not provide that ref, so CI threw ReferenceError on every steer case. * fix(session): allow git-layout mkdir in pinned checkpoint test SkipWorkspacePrep still omits the input/output bootstrap exec. The checkpoint script now mkdirs WORK_TREE and GIT_DIR, so the old "command must not contain mkdir" assertion was stale. * fix(session): block send while rewind holds the session lock BeginTurn now fails if the rewind key is held, so AgentQA cannot start during git reset. Knowledge-chat and executeQA check the same lock before persisting messages. composerLocked is still page-local. * fix(session): close send/rewind races and fail closed without a checkpoint Hold the turn lease before persist so rewind cannot truncate an in-flight send. TryLockRewind fails while a turn is live; emptying the conversation resets the workspace through the same git path as a SHA rewind. * fix(session): wrap rewind reset call to satisfy line length lint * fix(session): fail closed on a replaced sandbox and close leftover rewind holes Do not truncate history when the live workspace cannot follow the checkpoint, retry deletes after a successful git reset, and keep send and rewind exclusive even without a sandbox manager. * fix(session): address rewind review findings Correctness: - Adopt a pre-move /workspace/.git into SessionGitDir on first use. Sandboxes provisioned before the git dir moved out of the work tree still hold their checkpoints there, so every SHA recorded on those turns stopped resolving: rewind 500'd instead of truncating and fork's rollback failed on a bad object. Adoption is guarded on the new dir being absent and on the work-tree repo carrying the checkpointer's committer identity, so an agent's own `git init` in /workspace is left alone. - Only fail a send closed when BeginSessionTurn reports a rewind lock. Every other lease error degrades to running without a lease, as before rewind existed; a Redis blip on the lease script was rejecting the user's message. - Release an abandoned fork snapshot after the truncate lands, not before. Clearing the bootstrap column is a DB write a retry can redo; deleting the snapshot is not, and a delete that exhausted its retries left the fork with no workspace to boot from under a full transcript. - Re-acquire the rewind lock when a renew call errors, not just when it reports the lease lost. Sitting the tick out let a short Redis outage expire the 2m key mid-reset and hand the session to a second rewind. - Keep the history cursor when a post-rewind reload fails. Clearing it sent the next scroll-up back to the newest page, which the kept prefix already holds, instead of to older messages. Efficiency: - Add ListAssistantCheckpointsUpTo and use it to answer "which checkpoint does kept history still reach". Rewind was reading every message body and artifact row in the session to find one SHA. - Take the send-side turn lease once per request. The handler already holds it before persisting; QARequest.TurnLeaseHeld lets the QA services skip their own, so IM/MCP still take one and HTTP send stops doubling every rewind check and lease round trip. - Batch the suggestion delete behind DeleteByMessageIDs instead of one query per deleted message while the rewind lock is held. - Resolve the rewind affordance for the whole transcript in one pass rather than two list scans per rendered row on every streamed token. Cleanup: - Drop the SANDBOX_REPLACED skip reason, which the service never produces (it fail-closes with a 409), along with its copy in all five locales. - Drop GetMessagesBySession from rewindMessageStore; rewind never calls it. - Drop the unused chat.rewind.confirmTitle copy from all five locales. - Restore the chatHeader.toggleSandboxPanel wording this branch had changed unrelated to rewind. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-20 13:01:00 +00:00
func checkpointScript(workspace, gitDir, messageID string) string {
feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
return fmt.Sprintf(`set -e
feat(session): in-place rewind with workspace checkpoint reset (#3469) * refactor(session): extract shared workspace git reset helper Fork bootstrap and in-place rewind both need the same /workspace reset script. Move it out of fork_bootstrapper so rewind can reuse it without copying ExecShellCommand plumbing. * feat(message): add DeleteMessagesFrom for rewind truncation Rewind needs a composite created_at+id cursor so same-millisecond messages after the fork point are not left behind. Delete inside a transaction and return the rows so callers can log the count. * feat(session): add in-place rewind service Truncate the current session at a user or assistant message and git-reset the live sandbox when a reachable checkpoint exists. Reset failure is fail-closed so messages are never deleted ahead of the workspace. * feat(session): expose POST /sessions/:id/rewind Wire SessionRewindService through the session handler and container so the client can rewind in place. Busy sources map to 409; git reset failures stay 500. * feat(chat): add rewind API client and i18n copy Expose rewindSession with the same 180s timeout as fork, and add chat.rewind strings in all five locales so the confirm dialog is not hardcoded Chinese. * feat(chat): add rewind button with confirm dialog Offer in-place rewind next to fork on user and assistant messages. Confirm before truncating the thread, then reset locally and prefill the original question when the cut point is a user message. * fix(chat): confirm rewind with a compact popover Replace the full-page confirm dialog with a small popconfirm above the rewind button, and shorten the swagger description to satisfy line length. * fix(chat): skip markdown images with an empty destination Empty ![]() was rendered as <img src="">, which shows as a broken image in the reply. * fix(chat): clip sandbox panel slide-in and rename open tooltip Keep the enter animation inside the viewport so it cannot flash a document scrollbar and jump the page. Rename the header toggle from sandbox terminal to expand sidebar. * fix(session): 回滚时完成截断、互斥发送并重拉历史 客户端中断不再让 git reset 成功后留下未删的消息;reset/删消息前复查 busy,并锁住当前会话输入。成功后重拉历史,避免切会话预填串台和 steer 分段截错。 * fix(session): 工作区 git 外置,并让未开箱 fork 的回滚对齐 SHA checkpoint、回滚和 fork 共用 --git-dir=/var/lib/weknora/workspace.git,避免 rm -rf /workspace 丢掉历史。 未开箱分叉会话回滚时改写或清除 ForkBootstrap,避免第一次开箱仍 reset 到旧切点。 * fix(session): 回滚加会话锁,并堵住发送中回滚与脏 SHA 同一会话并发回滚互斥(进程内 + Redis),冲突返回 409。发送/流式中禁用回滚按钮;历史重拉成功后再改界面。未开箱 fork 的 checkpoint SHA 必须是 40 位 hex。工作区 git 只认外置 GIT_DIR,不再 mv/rm 根上的 .git。 * fix(session): 未开箱 fork 回滚成功时不要提示没有沙箱 ForkBootstrap 已对齐切点后返回 workspace_reset,前端走「已回滚」;清掉引导时改报 NO_CHECKPOINT。纯聊天仍用 NO_SANDBOX。 * fix(chat): stub composerLocked in steer interaction tests handleSteerMsg now bails when rewind locks the composer. The VM harness did not provide that ref, so CI threw ReferenceError on every steer case. * fix(session): allow git-layout mkdir in pinned checkpoint test SkipWorkspacePrep still omits the input/output bootstrap exec. The checkpoint script now mkdirs WORK_TREE and GIT_DIR, so the old "command must not contain mkdir" assertion was stale. * fix(session): block send while rewind holds the session lock BeginTurn now fails if the rewind key is held, so AgentQA cannot start during git reset. Knowledge-chat and executeQA check the same lock before persisting messages. composerLocked is still page-local. * fix(session): close send/rewind races and fail closed without a checkpoint Hold the turn lease before persist so rewind cannot truncate an in-flight send. TryLockRewind fails while a turn is live; emptying the conversation resets the workspace through the same git path as a SHA rewind. * fix(session): wrap rewind reset call to satisfy line length lint * fix(session): fail closed on a replaced sandbox and close leftover rewind holes Do not truncate history when the live workspace cannot follow the checkpoint, retry deletes after a successful git reset, and keep send and rewind exclusive even without a sandbox manager. * fix(session): address rewind review findings Correctness: - Adopt a pre-move /workspace/.git into SessionGitDir on first use. Sandboxes provisioned before the git dir moved out of the work tree still hold their checkpoints there, so every SHA recorded on those turns stopped resolving: rewind 500'd instead of truncating and fork's rollback failed on a bad object. Adoption is guarded on the new dir being absent and on the work-tree repo carrying the checkpointer's committer identity, so an agent's own `git init` in /workspace is left alone. - Only fail a send closed when BeginSessionTurn reports a rewind lock. Every other lease error degrades to running without a lease, as before rewind existed; a Redis blip on the lease script was rejecting the user's message. - Release an abandoned fork snapshot after the truncate lands, not before. Clearing the bootstrap column is a DB write a retry can redo; deleting the snapshot is not, and a delete that exhausted its retries left the fork with no workspace to boot from under a full transcript. - Re-acquire the rewind lock when a renew call errors, not just when it reports the lease lost. Sitting the tick out let a short Redis outage expire the 2m key mid-reset and hand the session to a second rewind. - Keep the history cursor when a post-rewind reload fails. Clearing it sent the next scroll-up back to the newest page, which the kept prefix already holds, instead of to older messages. Efficiency: - Add ListAssistantCheckpointsUpTo and use it to answer "which checkpoint does kept history still reach". Rewind was reading every message body and artifact row in the session to find one SHA. - Take the send-side turn lease once per request. The handler already holds it before persisting; QARequest.TurnLeaseHeld lets the QA services skip their own, so IM/MCP still take one and HTTP send stops doubling every rewind check and lease round trip. - Batch the suggestion delete behind DeleteByMessageIDs instead of one query per deleted message while the rewind lock is held. - Resolve the rewind affordance for the whole transcript in one pass rather than two list scans per rendered row on every streamed token. Cleanup: - Drop the SANDBOX_REPLACED skip reason, which the service never produces (it fail-closes with a 409), along with its copy in all five locales. - Drop GetMessagesBySession from rewindMessageStore; rewind never calls it. - Drop the unused chat.rewind.confirmTitle copy from all five locales. - Restore the chatHeader.toggleSandboxPanel wording this branch had changed unrelated to rewind. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-20 13:01:00 +00:00
%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)
feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
}
// Checkpoint commits /workspace and returns the resulting checkpoint, or nil
// when anything at all went wrong. It never returns an error by design: the
// caller runs on the turn-completion path and must not be blocked here.
func (c *WorkspaceCheckpointer) Checkpoint(
ctx context.Context, sessionID, sandboxID, messageID string,
) *types.SandboxCheckpoint {
if c == nil || c.runner == nil {
return nil
}
if strings.TrimSpace(sessionID) == "" || strings.TrimSpace(messageID) == "" {
return nil
}
// No bound sandbox means there is nothing to snapshot, and a checkpoint
// without a sandbox ID could never be validated at fork time anyway.
if strings.TrimSpace(sandboxID) == "" {
return nil
}
feat(sandbox): run unpinned Lite sessions on the host OS sandbox (#3549) * feat(sandbox): resolve workspace paths through WorkspaceLayout Keep remote sessions on the /workspace contract, while file, shell, and artifact code follow the session layout instead of hardcoded paths. * fix(sandbox): fail closed on host layout lookup and restore the shell blacklist Treat host vs remote as an explicit origin, refuse inspect outside ReadRoots, and skip collection when the output tree is missing or equals the project root. * fix(sandbox): close leftover fail-open holes in the layout path Keep host copy, collection, and prompt text from falling back to /workspace when a lookup fails or an adapter returns unclean roots. * fix(sandbox): satisfy golangci-lint on the layout helpers Wrap new copy and test lines to 120 columns, and add the exported comments revive requires. * fix(sandbox): gofmt the read_file layout copy wrap * feat(sandbox): add host as an OS-enforced backend type Host is not a named/pinnable config: each command is a fresh local process, unlike Docker, Cube, and E2B. * feat(session): persist Lite host workspace directory Empty means an auto-allocated folder. Standard edition leaves the column unused so the shared session model still loads. SQLite also gains the tenant skill tables Lite shell_exec already expects. * feat(localsandbox): adapt the host OS sandbox to session interfaces File tools stay outside Seatbelt and are bounded by PathGuard. A revoked project directory fails closed instead of allocating a replacement workspace. * feat(sandbox): run unpinned Lite sessions on the host backend Lite opts into host explicitly; web stays disabled when no named remote config exists. Host workspaces are not destroyed or auto-committed. * feat(desktop): pick and persist host project directories The native folder dialog is the authorization path; typed paths are rejected. settings.sandbox.host tells the client when this edition can use it. * fix(sandbox): fail closed on Lite host layout lookup misses Unpinned host sessions were described as /workspace when pin read or sandbox resolve failed. Prompts and attachment staging now share the same fallback so Lite never pretends the remote tree exists. * fix(frontend): keep settings.sandbox.host in sync with the backend keys TestDeploymentCapabilityKeysMatchFrontend requires the lists to match. Host stays fail-closed like docker so a missed probe does not show Lite-only UI. * fix(lint): satisfy golangci-lint on the host sandbox wiring Check c.Error, wrap lines over 120 columns, put context first on versionsWorkspace, and document exported adapter methods. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com>
2026-09-22 11:35:03 +00:00
if v, ok := c.runner.(WorkspaceVersioning); ok && !v.VersionsWorkspace(ctx, sessionID) {
return nil
}
feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
var result *sandbox.ExecuteResult
var err error
feat(session): in-place rewind with workspace checkpoint reset (#3469) * refactor(session): extract shared workspace git reset helper Fork bootstrap and in-place rewind both need the same /workspace reset script. Move it out of fork_bootstrapper so rewind can reuse it without copying ExecShellCommand plumbing. * feat(message): add DeleteMessagesFrom for rewind truncation Rewind needs a composite created_at+id cursor so same-millisecond messages after the fork point are not left behind. Delete inside a transaction and return the rows so callers can log the count. * feat(session): add in-place rewind service Truncate the current session at a user or assistant message and git-reset the live sandbox when a reachable checkpoint exists. Reset failure is fail-closed so messages are never deleted ahead of the workspace. * feat(session): expose POST /sessions/:id/rewind Wire SessionRewindService through the session handler and container so the client can rewind in place. Busy sources map to 409; git reset failures stay 500. * feat(chat): add rewind API client and i18n copy Expose rewindSession with the same 180s timeout as fork, and add chat.rewind strings in all five locales so the confirm dialog is not hardcoded Chinese. * feat(chat): add rewind button with confirm dialog Offer in-place rewind next to fork on user and assistant messages. Confirm before truncating the thread, then reset locally and prefill the original question when the cut point is a user message. * fix(chat): confirm rewind with a compact popover Replace the full-page confirm dialog with a small popconfirm above the rewind button, and shorten the swagger description to satisfy line length. * fix(chat): skip markdown images with an empty destination Empty ![]() was rendered as <img src="">, which shows as a broken image in the reply. * fix(chat): clip sandbox panel slide-in and rename open tooltip Keep the enter animation inside the viewport so it cannot flash a document scrollbar and jump the page. Rename the header toggle from sandbox terminal to expand sidebar. * fix(session): 回滚时完成截断、互斥发送并重拉历史 客户端中断不再让 git reset 成功后留下未删的消息;reset/删消息前复查 busy,并锁住当前会话输入。成功后重拉历史,避免切会话预填串台和 steer 分段截错。 * fix(session): 工作区 git 外置,并让未开箱 fork 的回滚对齐 SHA checkpoint、回滚和 fork 共用 --git-dir=/var/lib/weknora/workspace.git,避免 rm -rf /workspace 丢掉历史。 未开箱分叉会话回滚时改写或清除 ForkBootstrap,避免第一次开箱仍 reset 到旧切点。 * fix(session): 回滚加会话锁,并堵住发送中回滚与脏 SHA 同一会话并发回滚互斥(进程内 + Redis),冲突返回 409。发送/流式中禁用回滚按钮;历史重拉成功后再改界面。未开箱 fork 的 checkpoint SHA 必须是 40 位 hex。工作区 git 只认外置 GIT_DIR,不再 mv/rm 根上的 .git。 * fix(session): 未开箱 fork 回滚成功时不要提示没有沙箱 ForkBootstrap 已对齐切点后返回 workspace_reset,前端走「已回滚」;清掉引导时改报 NO_CHECKPOINT。纯聊天仍用 NO_SANDBOX。 * fix(chat): stub composerLocked in steer interaction tests handleSteerMsg now bails when rewind locks the composer. The VM harness did not provide that ref, so CI threw ReferenceError on every steer case. * fix(session): allow git-layout mkdir in pinned checkpoint test SkipWorkspacePrep still omits the input/output bootstrap exec. The checkpoint script now mkdirs WORK_TREE and GIT_DIR, so the old "command must not contain mkdir" assertion was stale. * fix(session): block send while rewind holds the session lock BeginTurn now fails if the rewind key is held, so AgentQA cannot start during git reset. Knowledge-chat and executeQA check the same lock before persisting messages. composerLocked is still page-local. * fix(session): close send/rewind races and fail closed without a checkpoint Hold the turn lease before persist so rewind cannot truncate an in-flight send. TryLockRewind fails while a turn is live; emptying the conversation resets the workspace through the same git path as a SHA rewind. * fix(session): wrap rewind reset call to satisfy line length lint * fix(session): fail closed on a replaced sandbox and close leftover rewind holes Do not truncate history when the live workspace cannot follow the checkpoint, retry deletes after a successful git reset, and keep send and rewind exclusive even without a sandbox manager. * fix(session): address rewind review findings Correctness: - Adopt a pre-move /workspace/.git into SessionGitDir on first use. Sandboxes provisioned before the git dir moved out of the work tree still hold their checkpoints there, so every SHA recorded on those turns stopped resolving: rewind 500'd instead of truncating and fork's rollback failed on a bad object. Adoption is guarded on the new dir being absent and on the work-tree repo carrying the checkpointer's committer identity, so an agent's own `git init` in /workspace is left alone. - Only fail a send closed when BeginSessionTurn reports a rewind lock. Every other lease error degrades to running without a lease, as before rewind existed; a Redis blip on the lease script was rejecting the user's message. - Release an abandoned fork snapshot after the truncate lands, not before. Clearing the bootstrap column is a DB write a retry can redo; deleting the snapshot is not, and a delete that exhausted its retries left the fork with no workspace to boot from under a full transcript. - Re-acquire the rewind lock when a renew call errors, not just when it reports the lease lost. Sitting the tick out let a short Redis outage expire the 2m key mid-reset and hand the session to a second rewind. - Keep the history cursor when a post-rewind reload fails. Clearing it sent the next scroll-up back to the newest page, which the kept prefix already holds, instead of to older messages. Efficiency: - Add ListAssistantCheckpointsUpTo and use it to answer "which checkpoint does kept history still reach". Rewind was reading every message body and artifact row in the session to find one SHA. - Take the send-side turn lease once per request. The handler already holds it before persisting; QARequest.TurnLeaseHeld lets the QA services skip their own, so IM/MCP still take one and HTTP send stops doubling every rewind check and lease round trip. - Batch the suggestion delete behind DeleteByMessageIDs instead of one query per deleted message while the rewind lock is held. - Resolve the rewind affordance for the whole transcript in one pass rather than two list scans per rendered row on every streamed token. Cleanup: - Drop the SANDBOX_REPLACED skip reason, which the service never produces (it fail-closes with a 409), along with its copy in all five locales. - Drop GetMessagesBySession from rewindMessageStore; rewind never calls it. - Drop the unused chat.rewind.confirmTitle copy from all five locales. - Restore the chatHeader.toggleSandboxPanel wording this branch had changed unrelated to rewind. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-20 13:01:00 +00:00
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.
result, err = runner.ExecShellCommandWithOptions(ctx, sessionID, command, sandbox.ShellExecOptions{
WorkDir: sandbox.SessionWorkspaceRoot, Timeout: workspaceCheckpointTimeout,
SkipWorkspacePrep: true, ExpectedSandboxID: sandboxID,
})
} else {
result, err = c.runner.ExecShellCommand(ctx, sessionID, command,
sandbox.SessionWorkspaceRoot, workspaceCheckpointTimeout, nil)
}
feat(session): fork conversations from a historical user message (#3304) * feat(session): add fork schema and history queries 为会话分叉增加数据模型与迁移,并提供截至分叉点的消息查询以及会话内的 request_id 配对。 * feat(sandbox): add git, fork snapshots, and bootstrap hook 沙箱镜像安装 git,Docker 快照使用独立的 fork 命名空间,并在首次创建会话沙箱时接入可选 bootstrap。 * feat(session): checkpoint workspace at the end of each turn 每轮结束后对沙箱 /workspace 打 git checkpoint,并避免 fork 后因 mtime 刷新重复挂上产物、以及附件仍绑在父会话而无法还原。 * feat(session): fork conversations and reap orphan snapshots 支持从历史 user 消息分叉会话、首次打开时从快照 bootstrap,并在失败或删除未打开的分叉时回收孤儿快照。 * feat(chat): add session fork entry, prefill, and badges 在用户消息上提供分叉入口,进入新会话时预填原问题,并展示降级提示与来源角标。 * style: add missing newline so session_fork_delete_test.go is gofmt-clean * fix(session): prune later git history when rolling a fork workspace back reset --hard 只还原工作区,分叉点之后的 commit 仍可被 checkout。校验 SHA 后丢掉其他 ref 并 gc,避免错误基线。 * style(session): clear golangci-lint findings on the session-fork diff Pre-push lints the whole PR against main; wrap long lines, check c.Error, and fix gofumpt/revive/staticcheck so the merge can be pushed. * fix(chat): show the fork button on hover without shifting the thread Overlay the action so revealing it no longer expands the user bubble and janks the messages below. * fix(chat): drop the fork landing banners Keep the original question prefilled; do not explain sandbox snapshot vs checkpoint on the new thread. * fix(agent): dedupe artifacts by content hash, not size Same-path same-size rewrites were skipped as restores. Keep path+mtime as the cheap skip, hash bytes when mtime moves, and stamp the restored mtime onto this session only. * feat(session): allow forking from an assistant answer User forks still copy history before the question and prefill it. Assistant forks copy through that reply and reuse its checkpoint, with a degrade tooltip when none exists. * fix(session): resolve parent attachments from a forked chat Fork copies attachment IDs onto the new messages but leaves temporary_documents on the parent. Preview and Get now look up those IDs on the fork's copied history instead of a scoped miss. * fix(agent): rewrite sandbox refs after a content-hash skip Fork restores change mtime on unchanged files, so Collect returns empty and named citations were left as sandbox: paths. Resolve those names against session artifacts, notify only real uploads, and stamp restored mtime only on the matching content hash. * fix(session): drop a dead fork snapshot and retry checkpoint rewrite Create from a missing template now abandons bootstrap so the next Resolve uses a normal sandbox. A failed checkpoint rewrite no longer marks the bootstrap consumed, which previously made nested forks SANDBOX_REPLACED. * fix(session): load forked parent attachments into the prompt ResolveForPrompt used session-scoped lookup, so copied parent attachment IDs passed Get but never reached the model. Use the same resolveInSession path as preview. * fix(chat): keep the user-message fork button visible The control was hover-only, which hid it on touch. Always show it, and drop the unused degrade tooltip. --------- Co-authored-by: hailongzhao <hailongzhao@tencent.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-17 06:20:18 +00:00
if err != nil {
logger.Warnf(ctx, "[WorkspaceCheckpointer] exec failed session=%s message=%s: %v",
sessionID, messageID, err)
return nil
}
if result == nil {
logger.Warnf(ctx, "[WorkspaceCheckpointer] nil result session=%s message=%s",
sessionID, messageID)
return nil
}
if result.ExitCode != 0 {
logger.Warnf(ctx,
"[WorkspaceCheckpointer] git exited %d session=%s message=%s stderr=%s",
result.ExitCode, sessionID, messageID, truncateForLog(result.Stderr))
return nil
}
sha := lastNonEmptyLine(result.Stdout)
if !gitSHAPattern.MatchString(sha) {
logger.Warnf(ctx,
"[WorkspaceCheckpointer] unexpected stdout tail session=%s message=%s tail=%q",
sessionID, messageID, truncateForLog(sha))
return nil
}
return &types.SandboxCheckpoint{
SandboxID: sandboxID,
CommitSHA: sha,
CommittedAt: time.Now().UTC(),
}
}
func lastNonEmptyLine(s string) string {
lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
for i := len(lines) - 1; i >= 0; i-- {
if line := strings.TrimSpace(lines[i]); line != "" {
return line
}
}
return ""
}
func truncateForLog(s string) string {
const limit = 256
s = strings.TrimSpace(s)
if len(s) <= limit {
return s
}
return s[:limit] + "…"
}