WeKnora/internal/handler/session/workspace_checkpoint_comple...

365 lines
12 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 session
import (
"context"
"errors"
"strings"
"testing"
"time"
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
"github.com/Tencent/WeKnora/internal/agent/skills"
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
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/sandbox"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type stubShellRunner struct {
stdout string
exitCode int
err error
calls int
}
func (s *stubShellRunner) ExecShellCommand(
_ context.Context, _ string, _, _ string, _ time.Duration, _ map[string]string,
) (*sandbox.ExecuteResult, error) {
s.calls++
if s.err != nil {
return nil, s.err
}
return &sandbox.ExecuteResult{ExitCode: s.exitCode, Stdout: s.stdout}, nil
}
type stubSandboxIDLookup struct {
id string
ok bool
}
func (s stubSandboxIDLookup) BoundSandboxID(context.Context, string) (string, bool) {
return s.id, s.ok
}
func newCheckpointHandler(
t *testing.T, runner service.SandboxShellRunner, lookup SandboxIDLookup,
) (*AgentStreamHandler, *types.Message) {
t.Helper()
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(), nil,
service.NewWorkspaceCheckpointer(runner), lookup,
)
return h, message
}
func completeEvent() event.Event {
return event.Event{Data: event.AgentCompleteData{MessageID: "m1", FinalAnswer: "done"}}
}
func TestHandleCompleteRecordsCheckpoint(t *testing.T) {
runner := &stubShellRunner{stdout: strings.Repeat("a", 40) + "\n"}
h, message := newCheckpointHandler(t, runner, stubSandboxIDLookup{id: "sbx-1", ok: true})
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Equal(t, 1, runner.calls)
require.NotNil(t, message.SandboxCheckpoint)
require.Equal(t, "sbx-1", message.SandboxCheckpoint.SandboxID)
require.Equal(t, strings.Repeat("a", 40), message.SandboxCheckpoint.CommitSHA)
}
// A failed checkpoint must never disturb the reply: the message still
// completes, it just carries no checkpoint and cannot serve as a fork point.
func TestHandleCompleteSurvivesCheckpointFailure(t *testing.T) {
runner := &stubShellRunner{err: errors.New("sandbox unreachable")}
h, message := newCheckpointHandler(t, runner, stubSandboxIDLookup{id: "sbx-1", ok: true})
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Nil(t, message.SandboxCheckpoint)
require.True(t, message.IsCompleted)
}
func TestHandleCompleteSkipsCheckpointWithoutBoundSandbox(t *testing.T) {
runner := &stubShellRunner{stdout: strings.Repeat("a", 40) + "\n"}
h, message := newCheckpointHandler(t, runner, stubSandboxIDLookup{ok: false})
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Zero(t, runner.calls)
require.Nil(t, message.SandboxCheckpoint)
}
func TestHandleCompleteWorksWithoutCheckpointerWired(t *testing.T) {
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(), nil, nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Nil(t, message.SandboxCheckpoint)
}
type capturingMessageService struct {
interfaces.MessageService
content string
checkpoint *types.SandboxCheckpoint
}
func (s *capturingMessageService) UpdateMessage(_ context.Context, message *types.Message) error {
if message == nil {
return nil
}
s.content = message.Content
if message.SandboxCheckpoint != nil {
cp := *message.SandboxCheckpoint
s.checkpoint = &cp
}
return nil
}
func (s *capturingMessageService) IndexMessageToKB(context.Context, string, string, string, string) {}
func TestQuickAnswerCompletionPersistsSandboxCheckpoint(t *testing.T) {
runner := &stubShellRunner{stdout: strings.Repeat("a", 40) + "\n"}
bus := event.NewEventBus()
message := &types.Message{
ID: "m1", SessionID: "s1", Role: "assistant", Content: "hello from quick answer",
}
streamHandler := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, bus,
nil, service.NewWorkspaceCheckpointer(runner), stubSandboxIDLookup{id: "sbx-1", ok: true},
)
streamHandler.Subscribe()
stub := &capturingMessageService{}
h := &Handler{messageService: stub}
h.completeQuickAnswerTurn(context.Background(), &sseStreamContext{
eventBus: bus,
streamHandler: streamHandler,
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
assistantMessage: message,
}, "", "")
require.Equal(t, 1, runner.calls, "quick-answer complete must checkpoint before persist")
require.NotNil(t, stub.checkpoint, "UpdateMessage must see SandboxCheckpoint")
require.Equal(t, "sbx-1", stub.checkpoint.SandboxID)
require.Equal(t, strings.Repeat("a", 40), stub.checkpoint.CommitSHA)
require.Equal(t, "hello from quick answer", stub.content, "complete event must not re-append the answer")
}
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
// layoutCollectSource records the directory CollectWithNotify asked to scan
// and only yields files that sit under the advertised OutputDir.
type layoutCollectSource struct {
layout sandbox.WorkspaceLayout
listedDirs []string
entries map[string][]sandbox.RemoteDirEntry
contents map[string][]byte
// layoutLookups guards against the collect target and the skip decision
// drifting back into two lookups that can disagree.
layoutLookups int
}
func (s *layoutCollectSource) ListSessionFiles(_ context.Context, _, dir string) ([]sandbox.RemoteDirEntry, error) {
s.listedDirs = append(s.listedDirs, dir)
return s.entries[dir], nil
}
func (s *layoutCollectSource) ReadSessionFile(_ context.Context, _ string, path string) ([]byte, error) {
if data, ok := s.contents[path]; ok {
return data, nil
}
return nil, errors.New("not found: " + path)
}
func (s *layoutCollectSource) SessionWorkspaceLayout(context.Context, string) (sandbox.WorkspaceLayout, error) {
s.layoutLookups++
return s.layout, nil
}
type collectDirFileService struct {
interfaces.FileService
}
func (s *collectDirFileService) SaveBytes(
_ context.Context, _ []byte, _ uint64, fileName string, _ bool,
) (string, error) {
return "fake://" + fileName, nil
}
func TestCompletionCollectsFromLayoutOutputDir(t *testing.T) {
layout := sandbox.WorkspaceLayout{
Origin: sandbox.WorkspaceOriginHost,
Root: "/Users/dev/proj",
OutputDir: "/Users/dev/AppData/s1/output",
}
source := &layoutCollectSource{
layout: layout,
entries: map[string][]sandbox.RemoteDirEntry{
layout.Root: {{
Name: "main.go", Path: layout.Root + "/src/main.go",
Type: sandbox.RemoteEntryFile, Size: 12,
ModTime: time.Date(2026, 7, 10, 10, 20, 33, 0, time.UTC),
}},
layout.OutputDir: {{
Name: "report.pptx", Path: layout.OutputDir + "/report.pptx",
Type: sandbox.RemoteEntryFile, Size: 4,
ModTime: time.Date(2026, 7, 10, 10, 20, 34, 0, time.UTC),
}},
},
contents: map[string][]byte{
layout.Root + "/src/main.go": []byte("package main"),
layout.OutputDir + "/report.pptx": []byte("PPTX"),
},
}
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(),
service.NewArtifactCollector(
source, &collectDirFileService{}, completionHistory{}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Equal(t, []string{layout.OutputDir}, source.listedDirs)
require.Len(t, message.Artifacts, 1)
require.Equal(t, "report.pptx", message.Artifacts[0].FileName)
require.Equal(t, 1, source.layoutLookups,
"the collect directory and the skip decision must come from one lookup")
}
func TestCompletionSkipsCollectWhenHostLayoutHasNoOutputDir(t *testing.T) {
source := &layoutCollectSource{
layout: sandbox.WorkspaceLayout{Origin: sandbox.WorkspaceOriginHost, Root: "/Users/dev/proj"},
entries: map[string][]sandbox.RemoteDirEntry{
"/Users/dev/proj": {{
Name: "main.go", Path: "/Users/dev/proj/src/main.go",
Type: sandbox.RemoteEntryFile, Size: 12,
ModTime: time.Date(2026, 7, 10, 10, 20, 33, 0, time.UTC),
}},
},
contents: map[string][]byte{
"/Users/dev/proj/src/main.go": []byte("package main"),
},
}
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(),
service.NewArtifactCollector(
source, &collectDirFileService{}, completionHistory{}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Empty(t, source.listedDirs)
require.Empty(t, message.Artifacts)
}
func TestCompletionSkipsCollectWhenOutputDirEqualsRoot(t *testing.T) {
source := &layoutCollectSource{
layout: sandbox.WorkspaceLayout{
Origin: sandbox.WorkspaceOriginHost,
Root: "/Users/dev/proj",
OutputDir: "/Users/dev/proj",
},
entries: map[string][]sandbox.RemoteDirEntry{
"/Users/dev/proj": {{
Name: "main.go", Path: "/Users/dev/proj/src/main.go",
Type: sandbox.RemoteEntryFile, Size: 12,
ModTime: time.Date(2026, 7, 10, 10, 20, 33, 0, time.UTC),
}},
},
contents: map[string][]byte{
"/Users/dev/proj/src/main.go": []byte("package main"),
},
}
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(),
service.NewArtifactCollector(
source, &collectDirFileService{}, completionHistory{}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Empty(t, source.listedDirs)
require.Empty(t, message.Artifacts)
}
type failingLayoutCollectSource struct {
listedDirs []string
}
func (s *failingLayoutCollectSource) ListSessionFiles(
_ context.Context, _, dir string,
) ([]sandbox.RemoteDirEntry, error) {
s.listedDirs = append(s.listedDirs, dir)
return nil, nil
}
func (s *failingLayoutCollectSource) ReadSessionFile(context.Context, string, string) ([]byte, error) {
return nil, errors.New("not found")
}
func (s *failingLayoutCollectSource) SessionWorkspaceLayout(context.Context, string) (sandbox.WorkspaceLayout, error) {
return sandbox.WorkspaceLayout{}, errors.New("layout unavailable")
}
func TestCompletionSkipsCollectWhenLayoutLookupFails(t *testing.T) {
source := &failingLayoutCollectSource{}
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(),
service.NewArtifactCollector(
source, &collectDirFileService{}, completionHistory{}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Empty(t, source.listedDirs)
require.Empty(t, message.Artifacts)
}
func TestCompletionCollectDirOnRemoteUsesArtifactOutputDir(t *testing.T) {
source := &remoteCollectSource{}
message := &types.Message{ID: "m1", SessionID: "s1", Role: "assistant"}
h := NewAgentStreamHandler(
context.Background(), "s1", "m1", "req1", 1, time.Now(),
message, &completionEventRecorder{}, event.NewEventBus(),
service.NewArtifactCollector(
source, &collectDirFileService{}, completionHistory{}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
require.NoError(t, h.handleComplete(context.Background(), completeEvent()))
require.Equal(t, []string{skills.ArtifactOutputDir()}, source.listedDirs)
}
// remoteCollectSource is a sandbox filesystem that does not advertise a
// workspace layout, matching remote backends that keep /workspace/output.
type remoteCollectSource struct {
listedDirs []string
}
func (s *remoteCollectSource) ListSessionFiles(_ context.Context, _, dir string) ([]sandbox.RemoteDirEntry, error) {
s.listedDirs = append(s.listedDirs, dir)
return nil, nil
}
func (s *remoteCollectSource) ReadSessionFile(context.Context, string, string) ([]byte, error) {
return nil, errors.New("not found")
}