chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,206 @@
package session
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
"academy/internal/event"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// capturingStreamManager records every appended event so a handler's output
// can be asserted without a real stream backend. Embedding the interface keeps
// everything else nil-panicky so an un-stubbed call fails loudly.
type capturingStreamManager struct {
interfaces.StreamManager
events []interfaces.StreamEvent
}
func (s *capturingStreamManager) AppendEvent(
_ context.Context, _, _ string, evt interfaces.StreamEvent,
) error {
s.events = append(s.events, evt)
return nil
}
// A failed tool execution is still a tool result: the SSE event must keep
// response_type=tool_result with success=false in its metadata, because
// response_type=error is reserved for internal agent failures (handleError).
func TestAgentStreamHandlerToolResultFailureKeepsToolResultType(t *testing.T) {
streams := &capturingStreamManager{}
h := NewAgentStreamHandler(
context.Background(), "sess-1", "msg-1", "req-1", 1, time.Now(),
&types.Message{}, streams, nil, nil, nil, nil,
)
err := h.handleToolResult(context.Background(), event.Event{
ID: "evt-1", Type: event.EventAgentToolResult,
Data: event.AgentToolResultData{
ToolName: "shell_exec",
ToolCallID: "call-1",
Success: false,
Error: "exit status 1",
},
})
require.NoError(t, err)
require.Len(t, streams.events, 1)
evt := streams.events[0]
require.Equal(t, types.ResponseTypeToolResult, evt.Type)
require.Equal(t, false, evt.Data["success"])
require.Equal(t, "exit status 1", evt.Data["error"])
require.Equal(t, "call-1", evt.Data["tool_call_id"])
}
// Internal error events keep response_type=error with done=true, so clients
// can still distinguish a crashed run from a failed tool call.
func TestAgentStreamHandlerInternalErrorKeepsErrorType(t *testing.T) {
streams := &capturingStreamManager{}
h := NewAgentStreamHandler(
context.Background(), "sess-1", "msg-1", "req-1", 1, time.Now(),
&types.Message{}, streams, nil, nil, nil, nil,
)
err := h.handleError(context.Background(), event.Event{
ID: "evt-err", Type: event.EventError,
Data: event.ErrorData{Stage: "think", Error: "llm unavailable"},
})
require.NoError(t, err)
require.Len(t, streams.events, 1)
evt := streams.events[0]
require.Equal(t, types.ResponseTypeError, evt.Type)
require.True(t, evt.Done)
}
func TestAgentStreamHandlerForwardsOperationDataChange(t *testing.T) {
streams := &capturingStreamManager{}
h := NewAgentStreamHandler(
context.Background(), "sess-1", "msg-1", "req-1", 1, time.Now(),
&types.Message{}, streams, nil, nil, nil, nil,
)
marker := map[string]any{"operation": "agent.delete", "area": "agent"}
err := h.handleToolResult(context.Background(), event.Event{
Type: event.EventAgentToolResult,
Data: event.AgentToolResultData{
ToolName: "run_operation", Success: true, Data: map[string]any{"data_change": marker},
},
})
require.NoError(t, err)
require.Len(t, streams.events, 1)
require.Equal(t, types.ResponseTypeToolResult, streams.events[0].Type)
require.Equal(t, marker, streams.events[0].Data["data_change"])
}
func TestAgentStreamHandlerProgressIsSeparateFromReasoningAndFinalAnswer(t *testing.T) {
streams := &capturingStreamManager{}
bus := event.NewEventBus()
h := NewAgentStreamHandler(
context.Background(),
"s",
"m",
"r",
1,
time.Now(),
&types.Message{},
streams,
bus,
nil,
nil,
nil,
)
h.Subscribe()
require.NoError(
t,
bus.Emit(
t.Context(),
event.Event{
ID: "progress-1",
Type: event.EventAgentProgress,
Data: event.AgentProgressData{Content: "Two tasks finished; one awaits approval.", Iteration: 3},
},
),
)
require.Len(t, streams.events, 1)
e := streams.events[0]
require.Equal(t, types.ResponseTypeProgress, e.Type)
require.Equal(t, "progress-1", e.Data["event_id"])
require.Equal(t, 3, e.Data["iteration"])
require.True(t, e.Done)
require.Empty(t, h.finalAnswer)
require.Empty(t, h.answerSegments)
require.Empty(t, h.eventStartTimes)
}
func TestPageButtonKeepsTheAnswerBeforeIt(t *testing.T) {
h := NewAgentStreamHandler(
context.Background(), "s", "m", "r", 1, time.Now(), &types.Message{},
&capturingStreamManager{}, nil, nil, nil, nil,
)
ctx := context.Background()
answer := func(id, content string) {
require.NoError(t, h.handleFinalAnswer(ctx, event.Event{
ID: id, Type: event.EventAgentFinalAnswer, Data: event.AgentFinalAnswerData{Content: content},
}))
}
call := func(name string, args map[string]any) {
require.NoError(t, h.handleToolCall(ctx, event.Event{
ID: "call", Type: event.EventAgentToolCall,
Data: event.AgentToolCallData{ToolCallID: "c-" + name, ToolName: name, Arguments: args},
}))
}
answer("a1", "the report")
call("open_page", nil)
call("open_page", map[string]any{"page": "agents"})
require.Equal(t, "the report", h.finalAnswer, "a page button follows the answer")
call("view_page", map[string]any{"page": "settings"})
require.Empty(t, h.finalAnswer, "viewing a page is more work, so the text was a preamble")
answer("a2", "second report")
require.NoError(t, h.handleProgress(ctx, event.Event{
ID: "a2", Type: event.EventAgentProgress, Data: event.AgentProgressData{Content: "second report"},
}))
require.Empty(t, h.finalAnswer, "progress with the answer's id retracts it")
}
func TestProtocolAnswerReplacementOnlyResetsMatchingSegment(t *testing.T) {
streams := &capturingStreamManager{}
h := NewAgentStreamHandler(
context.Background(),
"s",
"m",
"r",
1,
time.Now(),
&types.Message{},
streams,
nil,
nil,
nil,
nil,
)
send := func(id, content string, replace bool) {
require.NoError(
t,
h.handleFinalAnswer(context.Background(), event.Event{
ID: id, Type: event.EventAgentFinalAnswer,
Data: event.AgentFinalAnswerData{Content: content, Replace: replace},
}),
)
}
send("prior", "Earlier legitimate answer.", false)
send("current", "refs\nprivate prefix", false)
send("current", "", true)
send("current", "## 进展\ncomplete report", false)
require.Equal(t, "Earlier legitimate answer.", h.findAnswerSegment("prior").content)
require.Equal(t, "## 进展\ncomplete report", h.findAnswerSegment("current").content)
require.NotContains(t, h.finalAnswer, "private prefix")
require.Equal(t, true, streams.events[2].Data["replace"])
require.Equal(t, "current", streams.events[2].Data["event_id"])
}
@@ -0,0 +1,185 @@
package session
import (
"context"
"strings"
"testing"
"time"
"academy/internal/application/service"
"academy/internal/event"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type completionEventRecorder struct {
interfaces.StreamManager
events []interfaces.StreamEvent
}
func (s *completionEventRecorder) AppendEvent(_ context.Context, _, _ string, e interfaces.StreamEvent) error {
s.events = append(s.events, e)
return nil
}
type completionHistory struct{ previous []types.MessageArtifact }
func (s completionHistory) KnownArtifacts(context.Context, string) ([]types.MessageArtifact, error) {
return s.previous, nil
}
func (s completionHistory) RecordRestoredMtime(context.Context, string, string, time.Time, string) error {
return nil
}
func TestCompletionPublishesReconciledArtifactContent(t *testing.T) {
old := types.MessageArtifact{URL: "resource://dHZ_fFslfs0GgJGaJZGjGA", FileName: "deck.pptx", SourcePath: "/workspace/output/deck.pptx"}
next := old
next.URL = "resource://4N1nAo-FZZoDEExDQz2yoA"
stream := &completionEventRecorder{}
message := &types.Message{ID: "m", Content: "![deck](" + old.URL + ")", Artifacts: types.MessageArtifacts{next}}
handler := NewAgentStreamHandler(
context.Background(), "s", "m", "req", 1, next.CreatedAt,
message, stream, nil,
service.NewArtifactCollector(
nil, nil, completionHistory{[]types.MessageArtifact{old}}, nil, service.ArtifactCollectorConfig{},
),
nil, nil,
)
err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}})
require.NoError(t, err)
require.NoError(t, handler.publishCompletion(context.Background()))
last := stream.events[len(stream.events)-1]
require.Equal(t, types.ResponseTypeComplete, last.Type)
require.Equal(t, message.Content, last.Data["final_content"])
require.Contains(t, message.Content, old.URL)
require.Contains(t, message.Content, next.URL)
response := buildStreamResponse(last, "req")
require.Equal(t, message.Content, response.Data["final_content"])
}
// A turn that re-references a file it did not regenerate must still resolve the
// name. ArtifactCollector de-duplicates identical content, so this turn's
// `artifacts` is empty — and the rewrite used to be gated on it, leaving the
// body's `sandbox:<name>` unnormalized and rendering as a missing file.
//
// The first turn after a session fork is exactly this: the sandbox is rolled
// back to the fork point, so every file carried over from before the fork is
// skipped as unchanged.
func TestCompletionResolvesReferencesWhenNothingWasPersisted(t *testing.T) {
existing := types.MessageArtifact{
URL: types.BuildResourcePath(strings.Repeat("a", types.ResourceHandleLength)),
FileName: "report.pptx",
SourcePath: "/workspace/output/report.pptx",
}
stream := &completionEventRecorder{}
message := &types.Message{ID: "m", Content: "已生成 ![报告](sandbox:report.pptx)"}
handler := NewAgentStreamHandler(context.Background(), "s", "m", "req", 1, time.Time{},
message, stream, nil,
service.NewArtifactCollector(nil, nil, completionHistory{[]types.MessageArtifact{existing}}, nil, service.ArtifactCollectorConfig{}),
nil, nil)
err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}})
require.NoError(t, err)
require.NoError(t, handler.publishCompletion(context.Background()))
require.Len(t, message.Artifacts, 1, "the referenced file must be attached to this message")
require.Equal(t, existing.URL, message.Artifacts[0].URL)
require.Contains(t, message.Content, existing.URL)
require.NotContains(t, message.Content, "sandbox:")
last := stream.events[len(stream.events)-1]
require.Equal(t, types.ResponseTypeComplete, last.Type)
require.Equal(t, message.Content, last.Data["final_content"])
}
// KnownArtifacts is creation order (oldest first). A name with several
// versions must resolve to the latest recorded file — the one sitting in
// the sandbox at the fork point — not the first time that name appeared.
func TestCompletionResolvesNameToLatestKnownVersion(t *testing.T) {
old := types.MessageArtifact{
URL: types.BuildResourcePath(strings.Repeat("a", types.ResourceHandleLength)),
FileName: "report.pptx",
SourcePath: "/workspace/output/report.pptx",
}
latest := types.MessageArtifact{
URL: types.BuildResourcePath(strings.Repeat("b", types.ResourceHandleLength)),
FileName: "report.pptx",
SourcePath: "/workspace/output/report.pptx",
}
stream := &completionEventRecorder{}
message := &types.Message{ID: "m", Content: "已生成 ![报告](sandbox:report.pptx)"}
handler := NewAgentStreamHandler(context.Background(), "s", "m", "req", 1, time.Time{},
message, stream, nil,
service.NewArtifactCollector(nil, nil, completionHistory{[]types.MessageArtifact{old, latest}}, nil, service.ArtifactCollectorConfig{}),
nil, nil)
err := handler.handleComplete(context.Background(), event.Event{Data: event.AgentCompleteData{MessageID: "m"}})
require.NoError(t, err)
require.Len(t, message.Artifacts, 1)
require.Equal(t, latest.URL, message.Artifacts[0].URL)
require.Contains(t, message.Content, latest.URL)
require.NotContains(t, message.Content, old.URL)
require.NotContains(t, message.Content, "sandbox:")
}
type delegatedArtifactCatalog struct {
interfaces.ResourceCatalog
owners map[string]string
}
func (c *delegatedArtifactCatalog) Bind(_ context.Context, ref, _, owner, _ string) error {
c.owners[ref] = owner
return nil
}
func TestCompletionAttachesDelegatedFilesWithoutParentSandbox(t *testing.T) {
for _, withCollector := range []bool{false, true} {
name := "without_collector"
if withCollector {
name = "with_collector"
}
t.Run(name, func(t *testing.T) {
files := types.MessageArtifacts{
{
URL: "resource://" + strings.Repeat("a", 22), FileName: "report.md", FileType: ".md",
SourcePath: "collaboration://child-a/workspace/output/report.md",
},
{
URL: "resource://" + strings.Repeat("b", 22), FileName: "report.md", FileType: ".md",
SourcePath: "collaboration://child-b/workspace/output/report.md",
},
}
stream := &completionEventRecorder{}
message := &types.Message{ID: "parent-answer"}
catalog := &delegatedArtifactCatalog{owners: map[string]string{}}
var collector *service.ArtifactCollector
if withCollector {
collector = service.NewArtifactCollector(
nil, nil, completionHistory{}, catalog, service.ArtifactCollectorConfig{},
)
}
h := NewAgentStreamHandler(
context.Background(), "parent", message.ID, "req", 1, time.Now(),
message, stream, nil, collector, nil, nil,
)
answer := "[A](" + files[0].URL + ")\n\n[B](" + files[1].URL + ")"
require.NoError(t, h.handleComplete(context.Background(), event.Event{
Data: event.AgentCompleteData{MessageID: message.ID, FinalAnswer: answer, Artifacts: files},
}))
require.Equal(t, files, message.Artifacts, "persist both children even when their filenames coincide")
require.Equal(t, answer, message.Content, "keep each exact reference and the model's prose")
if withCollector {
for _, f := range files {
require.Equal(t, message.ID, catalog.owners[f.URL])
}
}
require.NoError(t, h.publishCompletion(context.Background()))
last := stream.events[len(stream.events)-1]
require.Equal(t, answer, last.Data["final_content"])
require.Equal(t, publicArtifactViews(files), last.Data["artifacts"])
})
}
}
+135
View File
@@ -0,0 +1,135 @@
package session
import (
stderrors "errors"
"net/http"
"strconv"
"strings"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
)
// DeleteMessageArtifact godoc
// @Summary 删除会话中的产物文件
// @Description 删除某条 assistant 消息生成的单个文件;all_versions=true 时连同本会话中该文件的所有历史版本一并删除
// @Tags 会话
// @Produce json
// @Param session_id path string true "会话ID"
// @Param message_id path string true "消息ID"
// @Param index path int true "产物在消息中的位置"
// @Param all_versions query bool false "是否删除该文件的所有版本"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /sessions/{session_id}/messages/{message_id}/artifacts/{index} [delete]
//
// Addressed by the same (message, index) coordinates as the download endpoint,
// so a client deletes exactly the row it was showing. The in-chat panel lists
// every version separately and omits all_versions; the artifact library folds
// versions into one entry and sets it.
func (h *Handler) DeleteMessageArtifact(c *gin.Context) {
sessionID := secutils.SanitizeForLog(paramSessionID(c))
messageID := secutils.SanitizeForLog(c.Param("message_id"))
index, err := strconv.Atoi(c.Param("index"))
if err != nil || index < 0 {
_ = c.Error(errors.NewBadRequestError("invalid artifact index"))
return
}
h.deleteArtifact(c, &types.ArtifactDeleteRequest{
SessionID: sessionID,
MessageID: messageID,
Index: index,
AllVersions: artifactAllVersions(c, false),
})
}
// DeleteLibraryArtifact godoc
// @Summary 删除产物库中的文件
// @Description 删除产物库中的一个文件。产物库一行代表一个文件的最新版本,默认连同该文件在本会话中的所有历史版本一并删除
// @Tags 会话
// @Produce json
// @Param session_id query string true "会话ID"
// @Param message_id query string true "消息ID"
// @Param index query int true "产物在消息中的位置"
// @Param all_versions query bool false "是否删除所有版本,默认 true"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /artifacts [delete]
//
// Versions default to being deleted together here: the library row IS the file,
// with a version count rather than a row per regeneration, so deleting one
// version would leave the entry in place showing the previous one.
func (h *Handler) DeleteLibraryArtifact(c *gin.Context) {
index, err := strconv.Atoi(c.Query("index"))
if err != nil || index < 0 {
_ = c.Error(errors.NewBadRequestError("invalid artifact index"))
return
}
h.deleteArtifact(c, &types.ArtifactDeleteRequest{
SessionID: secutils.SanitizeForLog(c.Query("session_id")),
MessageID: secutils.SanitizeForLog(c.Query("message_id")),
Index: index,
AllVersions: artifactAllVersions(c, true),
})
}
// artifactAllVersions reads the all_versions flag. The two routes differ only
// in what an absent flag means, so they share one parser: an explicit value is
// read the same way on both, and "1"/"TRUE"/"yes" cannot mean one thing here
// and another there.
func artifactAllVersions(c *gin.Context, whenAbsent bool) bool {
raw := strings.TrimSpace(c.Query("all_versions"))
if raw == "" {
return whenAbsent
}
parsed, err := strconv.ParseBool(raw)
if err != nil {
return whenAbsent
}
return parsed
}
// deleteArtifact runs the tombstone-then-reclaim sequence both delete routes
// share. The order matters: the rows are marked first, and only the rows this
// call actually claimed have their bytes reclaimed, so two concurrent deletes
// cannot both try to remove the same object.
func (h *Handler) deleteArtifact(c *gin.Context, req *types.ArtifactDeleteRequest) {
ctx := c.Request.Context()
result, err := h.messageService.DeleteSessionArtifact(ctx, req)
if err != nil {
// A session the caller does not own reads as absent, matching the rest
// of the session routes.
if stderrors.Is(err, errors.ErrSessionNotFound) {
_ = c.Error(errors.NewNotFoundError(err.Error()))
return
}
var appErr *errors.AppError
if stderrors.As(err, &appErr) {
_ = c.Error(appErr)
return
}
logger.Errorf(ctx, "delete artifact failed: session=%s message=%s idx=%d err=%v",
req.SessionID, req.MessageID, req.Index, err)
_ = c.Error(errors.NewInternalServerError(err.Error()))
return
}
// The rows are gone from every listing at this point. Reclaiming the bytes
// is best-effort cleanup, not part of the user-visible outcome, so its
// failures are logged rather than turned into a failed delete.
h.reclaimArtifactBlobs(ctx, types.MustTenantIDFromContext(ctx), result.Reclaim)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"file_name": result.FileName,
"deleted": result.Deleted,
},
})
}
@@ -0,0 +1,306 @@
package session
import (
"context"
stderrors "errors"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/service"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type stubMessageServiceForDelete struct {
interfaces.MessageService
got *types.ArtifactDeleteRequest
result *types.ArtifactDeleteResult
err error
}
func (s *stubMessageServiceForDelete) DeleteSessionArtifact(
_ context.Context, req *types.ArtifactDeleteRequest,
) (*types.ArtifactDeleteResult, error) {
s.got = req
return s.result, s.err
}
type deleteCatalogStub struct {
interfaces.ResourceCatalog
remaining int64
releaseErr error
released []string
resource *types.StoredResource
}
func (s *deleteCatalogStub) Release(_ context.Context, ref, ownerType, ownerID string) (int64, error) {
s.released = append(s.released, ref+"|"+ownerType+"|"+ownerID)
return s.remaining, s.releaseErr
}
func (s *deleteCatalogStub) ResolvePath(_ context.Context, ref string) (string, *types.StoredResource, error) {
if s.resource == nil {
return ref, nil, nil
}
return s.resource.PhysicalPath, s.resource, nil
}
type deletingFileService struct {
interfaces.FileService
deleted []string
}
func (f *deletingFileService) DeleteFile(_ context.Context, path string) error {
f.deleted = append(f.deleted, path)
return nil
}
func newArtifactDeleteRouter(h *Handler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(42)))
c.Next()
})
r.DELETE("/sessions/:id/messages/:message_id/artifacts/:index", h.DeleteMessageArtifact)
r.DELETE("/artifacts", h.DeleteLibraryArtifact)
return r
}
func TestDeleteMessageArtifactReclaimsTheBlob(t *testing.T) {
catalog := &deleteCatalogStub{
remaining: 0,
resource: &types.StoredResource{TenantID: 42, PhysicalPath: "local://42/exports/report.pptx"},
}
files := &deletingFileService{}
svc := &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
FileName: "报告.pptx",
Deleted: 1,
Reclaim: []types.ArtifactBlobRef{{URL: "resource://abc", MessageIDs: []string{"msg-1"}}},
}}
h := &Handler{messageService: svc, resourceCatalog: catalog, fileService: files}
w := httptest.NewRecorder()
newArtifactDeleteRouter(h).ServeHTTP(w,
httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/2", nil))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
if svc.got.SessionID != "sess-1" || svc.got.MessageID != "msg-1" || svc.got.Index != 2 {
t.Fatalf("service got %+v, want sess-1/msg-1/2", svc.got)
}
if svc.got.AllVersions {
t.Fatal("the in-chat panel lists versions separately, so all_versions defaults to false")
}
want := "resource://abc|" + types.ResourceOwnerMessage + "|msg-1"
if len(catalog.released) != 1 || catalog.released[0] != want {
t.Fatalf("released = %v, want [%s]", catalog.released, want)
}
// DeleteFile takes the stored reference; the catalog-backed service
// resolves it and marks the resource deleted itself.
if len(files.deleted) != 1 || files.deleted[0] != "resource://abc" {
t.Fatalf("deleted = %v, want [resource://abc]", files.deleted)
}
}
// A blob another owner still claims — an answer saved into a knowledge base, a
// later turn that re-attached the same file — must survive the delete.
func TestDeleteMessageArtifactKeepsBlobStillReferenced(t *testing.T) {
catalog := &deleteCatalogStub{remaining: 1}
files := &deletingFileService{}
h := &Handler{
messageService: &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
FileName: "shared.pptx",
Deleted: 1,
Reclaim: []types.ArtifactBlobRef{{URL: "resource://shared", MessageIDs: []string{"msg-1"}}},
}},
resourceCatalog: catalog,
fileService: files,
}
w := httptest.NewRecorder()
newArtifactDeleteRouter(h).ServeHTTP(w,
httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/0", nil))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if len(files.deleted) != 0 {
t.Fatalf("deleted = %v, want none: another owner still references the blob", files.deleted)
}
}
// An unreadable binding count keeps the bytes: an orphaned blob is reclaimable
// later, a file that vanished from someone else's document is not.
func TestDeleteMessageArtifactKeepsBlobWhenReleaseFails(t *testing.T) {
files := &deletingFileService{}
h := &Handler{
messageService: &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
Deleted: 1,
Reclaim: []types.ArtifactBlobRef{{URL: "resource://x", MessageIDs: []string{"msg-1"}}},
}},
resourceCatalog: &deleteCatalogStub{releaseErr: stderrors.New("catalog down")},
fileService: files,
}
w := httptest.NewRecorder()
newArtifactDeleteRouter(h).ServeHTTP(w,
httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/0", nil))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200: the rows are already tombstoned", w.Code)
}
if len(files.deleted) != 0 {
t.Fatalf("deleted = %v, want none", files.deleted)
}
}
// Deleting several versions can retire more than one claim on the same object:
// a later answer that re-attached an earlier file has its own binding. Every
// claim has to go before the bytes count as unreferenced.
func TestDeleteArtifactReleasesEveryOwningMessage(t *testing.T) {
catalog := &deleteCatalogStub{remaining: 0}
files := &deletingFileService{}
h := &Handler{
messageService: &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
FileName: "report.pptx",
Deleted: 2,
Reclaim: []types.ArtifactBlobRef{
{URL: "resource://abc", MessageIDs: []string{"msg-1", "msg-2"}},
},
}},
resourceCatalog: catalog,
fileService: files,
}
w := httptest.NewRecorder()
newArtifactDeleteRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
"/artifacts?session_id=sess-1&message_id=msg-1&index=0", nil))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
want := []string{
"resource://abc|" + types.ResourceOwnerMessage + "|msg-1",
"resource://abc|" + types.ResourceOwnerMessage + "|msg-2",
}
if len(catalog.released) != 2 || catalog.released[0] != want[0] || catalog.released[1] != want[1] {
t.Fatalf("released = %v, want %v", catalog.released, want)
}
if len(files.deleted) != 1 {
t.Fatalf("deleted = %v, want the object removed exactly once", files.deleted)
}
}
// The library row is a file with a version count, not one row per
// regeneration, so its delete takes every version unless told otherwise.
func TestDeleteLibraryArtifactDefaultsToAllVersions(t *testing.T) {
svc := &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{FileName: "a.pptx", Deleted: 3}}
h := &Handler{messageService: svc, fileService: &deletingFileService{}}
router := newArtifactDeleteRouter(h)
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
"/artifacts?session_id=sess-1&message_id=msg-1&index=0", nil))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
if !svc.got.AllVersions {
t.Fatal("library deletes take every version by default")
}
w = httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
"/artifacts?session_id=sess-1&message_id=msg-1&index=0&all_versions=false", nil))
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if svc.got.AllVersions {
t.Fatal("all_versions=false must be honoured")
}
}
// The two routes differ only in what an absent flag means. An explicit value
// must be read identically on both, so a client cannot have "1" mean one thing
// on one route and another elsewhere.
func TestAllVersionsIsParsedTheSameOnBothRoutes(t *testing.T) {
cases := []struct {
query string
session bool // in-chat route, absent => false
library bool // library route, absent => true
}{
{"", false, true},
{"&all_versions=true", true, true},
{"&all_versions=false", false, false},
{"&all_versions=1", true, true},
{"&all_versions=0", false, false},
{"&all_versions=TRUE", true, true},
{"&all_versions=F", false, false},
// Unparseable falls back to the route's default rather than to false.
{"&all_versions=perhaps", false, true},
}
for _, tc := range cases {
t.Run("q="+tc.query, func(t *testing.T) {
svc := &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{Deleted: 1}}
router := newArtifactDeleteRouter(&Handler{messageService: svc, fileService: &deletingFileService{}})
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
"/sessions/sess-1/messages/msg-1/artifacts/0?x=1"+tc.query, nil))
if w.Code != http.StatusOK {
t.Fatalf("session route status = %d, want 200", w.Code)
}
if svc.got.AllVersions != tc.session {
t.Fatalf("session route all_versions = %v, want %v", svc.got.AllVersions, tc.session)
}
w = httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
"/artifacts?session_id=sess-1&message_id=msg-1&index=0"+tc.query, nil))
if w.Code != http.StatusOK {
t.Fatalf("library route status = %d, want 200", w.Code)
}
if svc.got.AllVersions != tc.library {
t.Fatalf("library route all_versions = %v, want %v", svc.got.AllVersions, tc.library)
}
})
}
}
func TestDeleteArtifactErrorMapping(t *testing.T) {
cases := []struct {
name string
err error
want int
}{
{"already deleted or unknown", service.ErrArtifactNotFound, http.StatusNotFound},
{"session not owned", apperrors.ErrSessionNotFound, http.StatusNotFound},
{"repository failure", stderrors.New("db down"), http.StatusInternalServerError},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
h := &Handler{messageService: &stubMessageServiceForDelete{err: tc.err}}
w := httptest.NewRecorder()
newArtifactDeleteRouter(h).ServeHTTP(w,
httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/0", nil))
if w.Code != tc.want {
t.Fatalf("status = %d, want %d (body=%s)", w.Code, tc.want, w.Body.String())
}
})
}
}
func TestDeleteMessageArtifactRejectsBadIndex(t *testing.T) {
h := &Handler{messageService: &stubMessageServiceForDelete{}}
w := httptest.NewRecorder()
newArtifactDeleteRouter(h).ServeHTTP(w,
httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/-1", nil))
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400", w.Code)
}
}
@@ -0,0 +1,345 @@
package session
import (
stderrors "errors"
"mime"
"net/http"
"path/filepath"
"strconv"
"strings"
"academy/internal/application/access"
"academy/internal/errors"
"academy/internal/filetransport"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
)
// paramSessionID resolves the session-id URL parameter regardless of which
// wildcard name the current route uses. GET-tree routes bind :id (to align
// with /sessions/:id), while POST-tree routes typically bind :session_id.
// Handlers call this helper instead of hard-coding one name so the same
// function serves both trees.
func paramSessionID(c *gin.Context) string {
if v := c.Param("session_id"); v != "" {
return v
}
return c.Param("id")
}
// ListSessionArtifacts godoc
// @Summary 列出会话生成的产物文件
// @Description 返回本会话中所有 assistant 消息产生的技能产物元数据(不含 URL)
// @Tags 会话
// @Produce json
// @Param session_id path string true "会话ID"
// @Success 200 {object} map[string]interface{}
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /sessions/{session_id}/artifacts [get]
//
// The endpoint powers the drawer that lists every file generated in the
// session; it does NOT return the storage URL (only names/sizes/mtimes), so
// clients cannot reach around the download endpoint by reading a
// provider:// path from the API response.
//
// Deleted artifacts are skipped but still consume their index: the index IS the
// download address, so renumbering around a tombstone would point old links at
// the wrong file.
func (h *Handler) ListSessionArtifacts(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
if sessionID == "" {
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Ownership + tenant check: GetSession enforces both. Returning 404 for
// unknown / non-owned sessions matches the rest of the session routes.
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
artifacts, err := h.messageService.GetSessionArtifacts(ctx, sessionID)
if err != nil {
logger.Errorf(ctx, "list session artifacts failed: session=%s err=%v", sessionID, err)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
items := make([]artifactListItem, 0, len(artifacts))
for i, a := range artifacts {
if a.Deleted() {
continue
}
items = append(items, artifactListItem{
Index: i,
Handle: artifactHandle(a),
FileName: a.FileName,
FileType: a.FileType,
FileSize: a.FileSize,
SourcePath: a.SourcePath,
ModTime: a.ModTime,
CreatedAt: a.CreatedAt,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": items,
})
}
// ListMessageArtifacts returns just the artifacts attached to a single
// assistant message. Used by the "download files from this reply" button on
// each bot message.
//
// Same-tenant/same-owner check flows through h.sessionService.GetSession
// exactly like ListSessionArtifacts.
//
// @Router /sessions/{session_id}/messages/{message_id}/artifacts [get]
func (h *Handler) ListMessageArtifacts(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
messageID := secutils.SanitizeForLog(c.Param("message_id"))
if sessionID == "" || messageID == "" {
c.Error(errors.NewBadRequestError("session_id and message_id are required"))
return
}
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
msg, err := h.messageService.GetMessage(ctx, sessionID, messageID)
if err != nil || msg == nil {
c.Error(errors.NewNotFoundError("message not found"))
return
}
items := make([]artifactListItem, 0, len(msg.Artifacts))
for i, a := range msg.Artifacts {
if a.Deleted() {
continue
}
items = append(items, artifactListItem{
Index: i,
Handle: artifactHandle(a),
FileName: a.FileName,
FileType: a.FileType,
FileSize: a.FileSize,
SourcePath: a.SourcePath,
ModTime: a.ModTime,
CreatedAt: a.CreatedAt,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": items,
})
}
// DownloadMessageArtifact streams a single skill-generated file to the
// client. Clients reference the artifact by its position (:index) in the
// assistant message's Artifacts array; the storage URL never leaves the
// server so callers cannot pivot to arbitrary blobs.
//
// @Router /sessions/{session_id}/messages/{message_id}/artifacts/{index}/download [get]
func (h *Handler) DownloadMessageArtifact(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
messageID := secutils.SanitizeForLog(c.Param("message_id"))
indexParam := c.Param("index")
if sessionID == "" || messageID == "" || indexParam == "" {
c.Error(errors.NewBadRequestError("session_id, message_id and index are required"))
return
}
index, err := strconv.Atoi(indexParam)
if err != nil || index < 0 {
c.Error(errors.NewBadRequestError("invalid artifact index"))
return
}
// Ownership check: GetSession returns ErrSessionNotFound when the
// session doesn't belong to the calling tenant/user, so a 404 covers
// both "not found" and "forbidden" without leaking existence.
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.Error(errors.NewNotFoundError(err.Error()))
return
}
c.Error(errors.NewInternalServerError(err.Error()))
return
}
msg, err := h.messageService.GetMessage(ctx, sessionID, messageID)
if err != nil || msg == nil {
c.Error(errors.NewNotFoundError("message not found"))
return
}
if index >= len(msg.Artifacts) {
_ = c.Error(errors.NewNotFoundError("artifact index out of range"))
return
}
artifact := msg.Artifacts[index]
if artifact.Deleted() {
_ = c.Error(errors.NewNotFoundError("artifact deleted"))
return
}
if artifact.URL == "" {
_ = c.Error(errors.NewNotFoundError("artifact storage path missing"))
return
}
if h.fileService == nil {
c.Error(errors.NewInternalServerError("file service unavailable"))
return
}
file, err := access.ResolveMessageArtifact(ctx, msg, index, h.agentShareService, h.resourceCatalog,
access.MessageKBShareAuthorizer{ShareGuard: h.kbShareService, KBs: h.knowledgebaseService})
if err != nil {
_ = c.Error(errors.NewNotFoundError("artifact not accessible"))
return
}
fileService, ctx, ok := h.resolveArtifactFileService(
ctx, file.OwnerTenantID, file.Path, file.StorageBackendID, "artifact download",
)
if !ok {
_ = c.Error(errors.NewNotFoundError("artifact storage unavailable"))
return
}
reader, err := fileService.GetFile(ctx, file.Path)
if err != nil {
logger.Warnf(ctx, "artifact download read failed: session=%s message=%s idx=%d err=%v",
sessionID, messageID, index, err)
_ = c.Error(errors.NewNotFoundError("artifact blob missing"))
return
}
if err := filetransport.Serve(c.Writer, c.Request, reader, filetransport.Options{
Filename: artifact.FileName, Download: true, ContentType: mimeTypeFor(artifact.FileName),
Disposition: buildAttachmentHeader(artifact.FileName),
Size: artifact.FileSize,
CacheControl: "private, no-store",
}); err != nil {
logger.Warnf(
ctx,
"artifact download stream failed: session=%s message=%s idx=%d err=%v",
sessionID,
messageID,
index,
err,
)
}
}
// artifactListItem is the JSON shape returned by ListSessionArtifacts /
// ListMessageArtifacts. It carries the resource handle but never the storage
// path: the handle is the artifact's public identity — it is what the answer
// body references and what an authorizing proxy resolves — while the physical
// bucket/key stays server side.
type artifactListItem struct {
Index int `json:"index"`
// Handle is the artifact's `resource://<handle>` reference, matching the
// destinations in the message body. Empty when the deployment runs without
// a resource catalog, in which case the body references files by name.
Handle string `json:"handle,omitempty"`
FileName string `json:"file_name"`
FileType string `json:"file_type"`
FileSize int64 `json:"file_size"`
SourcePath string `json:"source_path"`
// time-typed fields serialise as RFC3339 strings — same convention as
// the rest of the messages API.
ModTime any `json:"mod_time"`
CreatedAt any `json:"created_at"`
}
// mimeTypeFor picks a Content-Type by extension and falls back to
// application/octet-stream so unknown types force a download prompt rather
// than being sniffed. Kept private to this file — the /files route has a
// stricter version with an SVG-neutralising branch; we don't need that here
// because Content-Disposition already blocks inline rendering.
func mimeTypeFor(name string) string {
ext := strings.ToLower(filepath.Ext(name))
if ext == "" {
return "application/octet-stream"
}
if ct := mime.TypeByExtension(ext); ct != "" {
return ct
}
return "application/octet-stream"
}
// buildAttachmentHeader returns a Content-Disposition value that preserves
// non-ASCII filenames (RFC 5987) while providing a safe fallback for
// ASCII-only clients.
func buildAttachmentHeader(name string) string {
// Strip control characters + quotes; keep the human-readable name.
ascii := strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f {
return -1
}
if r == '"' || r == '\\' {
return '_'
}
if r > 0x7e {
return -1
}
return r
}, name)
if ascii == "" {
ascii = "download"
}
encoded := (&urlPathEscaper{}).escape(name)
return "attachment; filename=\"" + ascii + "\"; filename*=UTF-8''" + encoded
}
// urlPathEscaper is a minimal RFC 3986 percent-encoder for the subset of
// bytes allowed in a filename*= value. We inline it to avoid importing
// net/url just for a two-line call, and because url.PathEscape encodes
// spaces as "+" (form-encoding) which HTTP clients then decode as literal
// "+" characters in the filename.
type urlPathEscaper struct{}
// escape percent-encodes every byte outside the "attr-char" grammar of RFC 5987.
// See https://datatracker.ietf.org/doc/html/rfc5987#section-3.2.1
func (urlPathEscaper) escape(s string) string {
var b strings.Builder
b.Grow(len(s))
const hex = "0123456789ABCDEF"
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case (c >= 'A' && c <= 'Z'), (c >= 'a' && c <= 'z'), (c >= '0' && c <= '9'):
b.WriteByte(c)
case c == '-' || c == '.' || c == '_' || c == '~':
b.WriteByte(c)
default:
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&0x0f])
}
}
return b.String()
}
// artifactHandle returns the artifact's `resource://<handle>` reference, or ""
// when the deployment stores artifacts without a resource catalog.
func artifactHandle(artifact types.MessageArtifact) string {
if handle, ok := types.ParseResourcePath(artifact.URL); ok {
return types.BuildResourcePath(handle)
}
return ""
}
@@ -0,0 +1,380 @@
package session
import (
"context"
stderrors "errors"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// -----------------------------------------------------------------------------
// Test doubles
//
// The download handler checks session ownership, persisted artifacts and
// source sharing before resolving the owner's file storage. We embed interfaces so the
// zero-value struct compiles, then override just the methods each test
// exercises. A stray call to an un-stubbed method deliberately nil-panics
// so the failure surfaces immediately.
// -----------------------------------------------------------------------------
type stubSessionServiceForArtifacts struct {
interfaces.SessionService
getSession func(ctx context.Context, id string) (*types.Session, error)
}
func (s *stubSessionServiceForArtifacts) GetSession(ctx context.Context, id string) (*types.Session, error) {
return s.getSession(ctx, id)
}
type stubMessageServiceForArtifacts struct {
interfaces.MessageService
getMessage func(ctx context.Context, sessionID, id string) (*types.Message, error)
getSessionArtifact func(ctx context.Context, sessionID string) (types.MessageArtifacts, error)
}
func (s *stubMessageServiceForArtifacts) GetMessage(ctx context.Context, sessionID, id string) (*types.Message, error) {
return s.getMessage(ctx, sessionID, id)
}
func (s *stubMessageServiceForArtifacts) GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error) {
if s.getSessionArtifact == nil {
return types.MessageArtifacts{}, nil
}
return s.getSessionArtifact(ctx, sessionID)
}
// fakeArtifactFileService serves canned bytes for a single URL.
type fakeArtifactFileService struct {
interfaces.FileService
url string
data []byte
calls int
}
func (f *fakeArtifactFileService) GetFile(_ context.Context, url string) (io.ReadCloser, error) {
f.calls++
if url != f.url {
return nil, stderrors.New("not found")
}
return io.NopCloser(strings.NewReader(string(f.data))), nil
}
type artifactCatalogStub struct {
interfaces.ResourceCatalog
resource *types.StoredResource
}
func (s *artifactCatalogStub) ResolvePath(context.Context, string) (string, *types.StoredResource, error) {
return s.resource.PhysicalPath, s.resource, nil
}
type artifactTenantStub struct {
interfaces.TenantService
t *testing.T
}
func (s *artifactTenantStub) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
if id != 7 || types.MustTenantIDFromContext(ctx) != 7 || types.CallerFromContext(ctx).TenantID != 42 {
s.t.Fatal("artifact storage must use its owner while preserving the caller")
}
return &types.Tenant{ID: id}, nil
}
type artifactStorageStub struct {
interfaces.StorageBackendResolver
t *testing.T
file interfaces.FileService
}
func (s *artifactStorageStub) ResolveFileService(
_ context.Context,
tenant *types.Tenant,
backendID, provider, _ string,
) (interfaces.FileService, string, error) {
if tenant.ID != 7 || backendID != "backend-7" || provider != "local" {
s.t.Fatalf("unexpected storage target: tenant=%d backend=%s provider=%s", tenant.ID, backendID, provider)
}
return s.file, provider, nil
}
func (f *fakeArtifactFileService) SaveFile(
_ context.Context,
_ *multipart.FileHeader,
_ uint64,
_ string,
) (string, error) {
return "", nil
}
func (f *fakeArtifactFileService) SaveBytes(_ context.Context, _ []byte, _ uint64, _ string, _ bool) (string, error) {
return "", nil
}
func (f *fakeArtifactFileService) GetFileURL(_ context.Context, _ string) (string, error) {
return "", nil
}
func (f *fakeArtifactFileService) DeleteFile(_ context.Context, _ string) error {
return nil
}
// -----------------------------------------------------------------------------
// Router builder
// -----------------------------------------------------------------------------
func newArtifactTestRouter(h *Handler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(42)))
c.Next()
})
// Match the production route's wildcard names (see router.go — GET tree
// binds :id to align with /sessions/:id) so paramSessionID resolves via
// the same code path exercised in prod.
r.GET("/sessions/:id/artifacts", h.ListSessionArtifacts)
r.GET("/sessions/:id/messages/:message_id/artifacts", h.ListMessageArtifacts)
r.GET("/sessions/:id/messages/:message_id/artifacts/:index/download", h.DownloadMessageArtifact)
return r
}
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
func TestDownloadMessageArtifact_HappyPath(t *testing.T) {
sessionID := "sess-1"
messageID := "msg-1"
url := "local://42/exports/report.pptx"
body := []byte("PPTX-BYTES")
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, id string) (*types.Session, error) {
if id != sessionID {
return nil, apperrors.ErrSessionNotFound
}
return &types.Session{ID: id, TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getMessage: func(_ context.Context, sid, mid string) (*types.Message, error) {
if sid != sessionID || mid != messageID {
return nil, nil
}
return &types.Message{
ID: mid, SessionID: sid,
Artifacts: types.MessageArtifacts{{
URL: url,
FileName: "报告.pptx", // non-ASCII to exercise RFC 5987 encoding
FileType: ".pptx",
FileSize: int64(len(body)),
}},
}, nil
},
},
fileService: &fakeArtifactFileService{url: url, data: body},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/0/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
if got := w.Body.String(); got != string(body) {
t.Fatalf("body = %q, want %q", got, string(body))
}
cd := w.Header().Get("Content-Disposition")
if !strings.HasPrefix(cd, "attachment;") {
t.Fatalf("Content-Disposition = %q, want attachment prefix", cd)
}
if !strings.Contains(cd, "filename*=UTF-8''") {
t.Fatalf("Content-Disposition = %q, want RFC 5987 filename*", cd)
}
if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
}
}
func TestDownloadMessageArtifact_SessionNotOwnedReturns404(t *testing.T) {
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return nil, apperrors.ErrSessionNotFound
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-x/messages/msg-x/artifacts/0/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", w.Code)
}
}
func TestDownloadMessageArtifact_SourceStorageAndShareRevocation(t *testing.T) {
const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
const physical = "local://7/exports/report.pdf"
shares := &resolveAgentShareStub{agent: &types.CustomAgent{ID: "agent", TenantID: 7}}
ownerFiles := &fakeArtifactFileService{url: physical, data: []byte("PDF-BYTES")}
globalFiles := &fakeArtifactFileService{}
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(context.Context, string) (*types.Session, error) {
return &types.Session{ID: "sess-1", TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getMessage: func(context.Context, string, string) (*types.Message, error) {
return &types.Message{
ID: "msg-1", AgentID: "agent", AgentTenantID: 7,
Artifacts: types.MessageArtifacts{{URL: ref, FileName: "report.pdf"}},
}, nil
},
},
agentShareService: shares,
resourceCatalog: &artifactCatalogStub{resource: &types.StoredResource{
TenantID: 7, PhysicalPath: physical, StorageBackendID: "backend-7",
}},
tenantService: &artifactTenantStub{t: t},
storageResolver: &artifactStorageStub{t: t, file: ownerFiles},
fileService: globalFiles,
}
router := newArtifactTestRouter(h)
request := func() *httptest.ResponseRecorder {
w := httptest.NewRecorder()
router.ServeHTTP(
w,
httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/0/download", nil),
)
return w
}
w := request()
if w.Code != http.StatusOK || w.Body.String() != "PDF-BYTES" ||
w.Header().Get("Cache-Control") != "private, no-store" {
t.Fatalf("status=%d body=%q cache=%q", w.Code, w.Body.String(), w.Header().Get("Cache-Control"))
}
shares.agent = nil
w = request()
if w.Code != http.StatusNotFound || ownerFiles.calls != 1 || globalFiles.calls != 0 {
t.Fatalf(
"revoked artifact: status=%d owner reads=%d global reads=%d",
w.Code,
ownerFiles.calls,
globalFiles.calls,
)
}
}
func TestDownloadMessageArtifact_IndexOutOfRange(t *testing.T) {
sessionID := "sess-1"
messageID := "msg-1"
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return &types.Session{ID: sessionID, TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getMessage: func(_ context.Context, _, _ string) (*types.Message, error) {
return &types.Message{ID: messageID, SessionID: sessionID, Artifacts: types.MessageArtifacts{}}, nil
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/7/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404 for out-of-range index", w.Code)
}
}
func TestDownloadMessageArtifact_InvalidIndex(t *testing.T) {
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return &types.Session{ID: "sess-1", TenantID: 42}, nil
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/messages/msg-1/artifacts/not-a-number/download", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 for non-integer index", w.Code)
}
}
func TestListSessionArtifacts_StripsURL(t *testing.T) {
h := &Handler{
sessionService: &stubSessionServiceForArtifacts{
getSession: func(_ context.Context, _ string) (*types.Session, error) {
return &types.Session{ID: "sess-1", TenantID: 42}, nil
},
},
messageService: &stubMessageServiceForArtifacts{
getSessionArtifact: func(_ context.Context, _ string) (types.MessageArtifacts, error) {
return types.MessageArtifacts{
{URL: "fake://internal/1", FileName: "a.txt", FileSize: 1, CreatedAt: time.Now()},
}, nil
},
},
}
router := newArtifactTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/sessions/sess-1/artifacts", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
}
// The URL must not appear in the response body: it's an internal
// storage path and leaking it defeats the download endpoint's
// ownership check.
if strings.Contains(w.Body.String(), "fake://internal/1") {
t.Fatalf("response body leaked storage URL: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), "a.txt") {
t.Fatalf("response body missing file name: %s", w.Body.String())
}
}
func TestBuildAttachmentHeader_CJK(t *testing.T) {
// The RFC 5987 filename* segment must percent-encode every non-attr-char
// byte so downstream browsers preserve "报告.pptx" instead of mojibake.
got := buildAttachmentHeader("报告.pptx")
if !strings.Contains(got, "filename=") {
t.Fatalf("missing ASCII filename fallback: %q", got)
}
if !strings.Contains(got, "filename*=UTF-8''") {
t.Fatalf("missing RFC 5987 filename*: %q", got)
}
// Non-ASCII bytes must be percent-encoded (never appear literally).
if strings.ContainsRune(got, '报') {
t.Fatalf("filename* contains raw CJK: %q", got)
}
}
func (s *artifactCatalogStub) GetMessageFileBindings(
_ context.Context,
_ uint64,
_, messageID string,
) (*types.MessageFileBindings, error) {
return &types.MessageFileBindings{MessageArtifact: messageID == "msg-1"}, nil
}
@@ -0,0 +1,61 @@
package session
import (
"net/http"
"strings"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
// ListArtifactLibrary godoc
// @Summary 列出我的产物
// @Description 跨会话列出当前用户可见会话中技能生成的文件,每个文件只返回最新版本(不含存储 URL)
// @Tags 会话
// @Produce json
// @Param keyword query string false "按文件名过滤"
// @Param file_types query string false "逗号分隔的扩展名,如 .pdf,.pptx"
// @Param page query int false "页码"
// @Param page_size query int false "每页数量(最大 100)"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Security ApiKeyAuth
// @Router /artifacts [get]
//
// Items carry session_id, message_id and index so the client downloads
// through the per-session endpoint, which re-runs the ownership check.
func (h *Handler) ListArtifactLibrary(c *gin.Context) {
ctx := c.Request.Context()
var pagination types.Pagination
if err := c.ShouldBindQuery(&pagination); err != nil {
_ = c.Error(errors.NewBadRequestError(err.Error()))
return
}
var fileTypes []string
if raw := c.Query("file_types"); raw != "" {
fileTypes = strings.Split(raw, ",")
}
result, err := h.messageService.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{
Keyword: c.Query("keyword"),
FileTypes: fileTypes,
Page: pagination.Page,
PageSize: pagination.PageSize,
})
if err != nil {
logger.Errorf(ctx, "list artifact library failed: %v", err)
_ = c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result.Data,
"total": result.Total,
"page": result.Page,
"page_size": result.PageSize,
})
}
@@ -0,0 +1,439 @@
package session
import (
"net/url"
"path"
"regexp"
"strings"
"academy/internal/types"
)
// Models routinely reference the files they generated in the sandbox from
// their final answer, most often as a Markdown image (`![评分](市场画像评分.html)`).
// A bare file name resolves to nothing once the sandbox is gone, so this is the
// boundary where an answer's transient, sandbox-local references are normalized
// into the one reference form that survives: `resource://<handle>`.
//
// The handle is the same identity every other stored file uses (knowledge-base
// images, chat attachments), which is what makes a saved answer keep working:
// re-binding the handle to a knowledge entry is enough, with no copy and no
// second rewrite. It is also opaque — the physical storage path stays server
// side, and every read still goes through an authorizing proxy.
//
// A deployment without the resource catalog has no handle to point at, so those
// references are normalized to the canonical `sandbox:<name>` spelling instead
// and resolved by name against the message's own artifact list. That keeps the
// answer readable in the chat, and only there.
//
// The rewrite runs once per turn, after ArtifactCollector has drained
// /workspace/output, so every artifact already has its handle.
// fencedOrInlineCodeRE splits content so destinations inside code samples are
// never rewritten — a documentation snippet showing the syntax must survive.
var fencedOrInlineCodeRE = regexp.MustCompile("(?s)(```.*?```|~~~.*?~~~|`[^`\n]*`)")
// schemeRE matches an already-qualified URL (http://, resource://, data:, …).
var schemeRE = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.\-]*:`)
// titleSuffixRE splits the optional title off a link destination
// (`file.png "caption"`).
var titleSuffixRE = regexp.MustCompile(`(?s)^(.*?)(\s+(?:"[^"]*"|'[^']*'))$`)
// rewriteArtifactReferences replaces every Markdown link/image destination that
// names one of the turn's artifacts with that artifact's stable reference.
//
// Three destination spellings are accepted, because models are inconsistent
// about the prefix even when the prompt asks for one:
//
// ![评分](sandbox:市场画像评分.html)
// ![评分](市场画像评分.html)
// ![评分](./output/市场画像评分.html)
//
// Anything else — an http URL, a resource:// handle the model copied from
// context, an unknown file name — is returned unchanged so existing behaviour
// (knowledge-base images, web links) is untouched.
func rewriteArtifactReferences(content string, artifacts types.MessageArtifacts) string {
if content == "" || len(artifacts) == 0 {
return content
}
byName := artifactRefByName(artifacts)
if len(byName) == 0 {
return content
}
parts := fencedOrInlineCodeRE.Split(content, -1)
if len(parts) == 1 {
return rewriteArtifactReferencesInSegment(content, byName)
}
code := fencedOrInlineCodeRE.FindAllString(content, -1)
var out strings.Builder
out.Grow(len(content))
for i, part := range parts {
out.WriteString(rewriteArtifactReferencesInSegment(part, byName))
if i < len(code) {
out.WriteString(code[i])
}
}
return out.String()
}
// rewriteArtifactReferencesInSegment walks every inline Markdown link/image in
// one non-code segment and rebinds the ones that name an artifact.
//
// Destinations are located by matching parentheses rather than by regex,
// because skill-generated file names routinely contain both spaces and
// parentheses (`腾讯控股(00700) 成交量_838ccc.html`). A regex that stops at the
// first space or paren would capture half the name and never match.
func rewriteArtifactReferencesInSegment(segment string, byName map[string]string) string {
if segment == "" || !strings.Contains(segment, "](") {
return segment
}
var out strings.Builder
out.Grow(len(segment))
cursor := 0
for cursor < len(segment) {
relative := strings.Index(segment[cursor:], "](")
if relative < 0 {
break
}
closeBracket := cursor + relative
open := closeBracket + 1
inner, end, ok := scanLinkDestination(segment, open)
if !ok || !hasLinkLabelBefore(segment, closeBracket) {
out.WriteString(segment[cursor : open+1])
cursor = open + 1
continue
}
destination, title := splitDestinationTitle(inner)
ref, matched := lookupArtifactRef(destination, byName, markdownImageBefore(segment, closeBracket))
if !matched {
out.WriteString(segment[cursor : end+1])
cursor = end + 1
continue
}
out.WriteString(segment[cursor : open+1])
out.WriteString(ref)
out.WriteString(title)
out.WriteString(")")
cursor = end + 1
}
out.WriteString(segment[cursor:])
return out.String()
}
// scanLinkDestination returns the text between the `(` at openIndex and its
// matching `)`, plus the index of that closing paren. A destination never spans
// a line break, so a newline ends the scan unsuccessfully.
func scanLinkDestination(text string, openIndex int) (string, int, bool) {
depth := 1
for i := openIndex + 1; i < len(text); i++ {
switch text[i] {
case '\n':
return "", 0, false
case '(':
depth++
case ')':
depth--
if depth == 0 {
return text[openIndex+1 : i], i, true
}
}
}
return "", 0, false
}
// hasLinkLabelBefore reports whether `](` is preceded by a `[` on the same
// line, i.e. whether this really is a link rather than incidental punctuation.
func hasLinkLabelBefore(text string, closeBracketIndex int) bool {
for i := closeBracketIndex - 1; i >= 0; i-- {
switch text[i] {
case '\n':
return false
case '[':
return true
}
}
return false
}
// splitDestinationTitle separates `dest "title"` into its two parts, returning
// the title with its leading whitespace so it can be re-emitted verbatim.
func splitDestinationTitle(inner string) (string, string) {
if groups := titleSuffixRE.FindStringSubmatch(inner); groups != nil {
return strings.TrimSpace(groups[1]), groups[2]
}
return strings.TrimSpace(inner), ""
}
func markdownImageBefore(text string, closeBracketIndex int) bool {
for i := closeBracketIndex - 1; i >= 0; i-- {
switch text[i] {
case '\n':
return false
case '[':
return i > 0 && text[i-1] == '!'
}
}
return false
}
func looksLikeSandboxOutputPath(candidate string) bool {
c := strings.TrimPrefix(strings.TrimSpace(candidate), "./")
c = strings.TrimPrefix(c, "/")
return strings.HasPrefix(c, "workspace/output/") || strings.HasPrefix(c, "output/")
}
// lookupArtifactRef resolves one Markdown destination to an artifact reference.
func lookupArtifactRef(destination string, byName map[string]string, image bool) (string, bool) {
name, ok := artifactDestinationName(destination, image)
if !ok {
return "", false
}
ref, ok := byName[name]
return ref, ok
}
// artifactDestinationName normalizes one Markdown link/image destination down to
// the sandbox-output file name it names. ok is false when the destination is not
// a sandbox-local file name at all — a real URL, a resource:// handle, a bare
// name in an ordinary link, or incidental prose punctuation.
func artifactDestinationName(destination string, image bool) (string, bool) {
candidate := strings.TrimSpace(destination)
if candidate == "" {
return "", false
}
// Trim the optional angle-bracket form Markdown allows around a
// destination: `[x](<name with space>)` — kept for completeness even
// though the outer regex rejects inner whitespace.
candidate = strings.TrimPrefix(strings.TrimSuffix(candidate, ">"), "<")
hadSandboxPrefix := false
for _, prefix := range []string{"sandbox://", "sandbox:"} {
if len(candidate) >= len(prefix) && strings.EqualFold(candidate[:len(prefix)], prefix) {
candidate = candidate[len(prefix):]
hadSandboxPrefix = true
break
}
}
// A destination that already carries a scheme is a real URL, not a file
// name. `sandbox:` is the one exception and was stripped above.
if !hadSandboxPrefix && schemeRE.MatchString(candidate) {
return "", false
}
// Models percent-encode non-ASCII names about half the time.
if decoded, err := url.PathUnescape(candidate); err == nil {
candidate = decoded
}
candidate = strings.TrimSpace(candidate)
// Bare names are rewritten for images (`![chart](a.html)`) because that is
// how models actually cite generated files. Ordinary links (`[docs](README.md)`)
// are left alone unless they already carry a sandbox prefix or path —
// otherwise a colliding artifact name would hijack a real hyperlink.
if !hadSandboxPrefix && !image && !looksLikeSandboxOutputPath(candidate) {
return "", false
}
// Directory prefixes (`./`, `output/`, `/workspace/output/`) carry no
// information the artifact list does not already have.
candidate = path.Base(candidate)
if candidate == "" || candidate == "." || candidate == "/" {
return "", false
}
return candidate, true
}
// forEachArtifactDestination calls fn with the normalized file name of every
// link/image destination in content. Destinations inside code spans or fences
// are skipped, mirroring rewriteArtifactReferences.
func forEachArtifactDestination(content string, fn func(name string)) {
if content == "" || !strings.Contains(content, "](") {
return
}
// Split returns only the non-code segments (Go does not interleave the
// matched fences the way a capturing-group Python split would). Walk
// every part; skipping odd indexes would drop citations after the first
// fence, which rewriteArtifactReferences still rewrites.
for _, part := range fencedOrInlineCodeRE.Split(content, -1) {
walkSegmentDestinations(part, fn)
}
}
func walkSegmentDestinations(segment string, fn func(name string)) {
cursor := 0
for cursor < len(segment) {
relative := strings.Index(segment[cursor:], "](")
if relative < 0 {
return
}
closeBracket := cursor + relative
open := closeBracket + 1
inner, end, ok := scanLinkDestination(segment, open)
if !ok || !hasLinkLabelBefore(segment, closeBracket) {
cursor = open + 1
continue
}
destination, _ := splitDestinationTitle(inner)
if name, ok := artifactDestinationName(destination, markdownImageBefore(segment, closeBracket)); ok {
fn(name)
}
cursor = end + 1
}
}
// referencedArtifacts returns the candidates the answer body names, in
// candidate order.
//
// A candidate is named when the body carries its resource:// handle, or when a
// link/image destination resolves to its file name — the same spellings
// rewriteArtifactReferences accepts. Matching goes through the Markdown
// destination rules rather than a substring search, so a file that merely
// appears in prose is not treated as a reference.
//
// Candidates are matched in the order given: listing this turn's artifacts
// first lets a regenerated file shadow the older version of itself, so only an
// explicit handle reference still pulls the old version in.
func referencedArtifacts(content string, candidates types.MessageArtifacts) types.MessageArtifacts {
if content == "" || len(candidates) == 0 {
return nil
}
matched := make([]bool, len(candidates))
for _, handle := range types.ScanResourceReferences(content) {
for i := range candidates {
if candidates[i].URL == handle {
matched[i] = true
break
}
}
}
nameToIndex := make(map[string]int, len(candidates))
for i := range candidates {
name := strings.TrimSpace(candidates[i].FileName)
if name == "" {
continue
}
if _, exists := nameToIndex[name]; exists {
continue
}
nameToIndex[name] = i
}
if len(nameToIndex) > 0 {
forEachArtifactDestination(content, func(name string) {
if i, ok := nameToIndex[name]; ok {
matched[i] = true
}
})
}
var out types.MessageArtifacts
for i := range candidates {
if matched[i] {
out = append(out, candidates[i])
}
}
return out
}
// artifactRefByName maps each artifact's file name to the reference that
// replaces it in the answer. A duplicate name keeps the first occurrence:
// silently preferring the later file would make the reference point at
// something the model did not describe.
func artifactRefByName(artifacts types.MessageArtifacts) map[string]string {
byName := make(map[string]string, len(artifacts))
for _, artifact := range artifacts {
name := strings.TrimSpace(artifact.FileName)
if name == "" {
continue
}
if _, exists := byName[name]; exists {
continue
}
byName[name] = artifactReference(artifact)
}
return byName
}
// artifactReference returns the destination an answer should carry for one
// artifact: its catalog handle when the deployment has a resource registry,
// otherwise the canonical chat-only `sandbox:<name>` form.
//
// The raw storage path is never a candidate. It names a bucket and key, which
// is both an information leak and useless to a client that has no credentials
// for the object store.
func artifactReference(artifact types.MessageArtifact) string {
if handle, ok := types.ParseResourcePath(artifact.URL); ok {
return types.BuildResourcePath(handle)
}
return "sandbox:" + strings.TrimSpace(artifact.FileName)
}
// artifactsNewestFirst returns a copy of artifacts in reverse order so the
// latest recorded version of a name is first. KnownArtifacts is creation
// order (oldest first); a hash-skipped citation must bind the fork-point
// file, not the first time that name appeared. A copy is required: reversing
// in place would mutate the store's backing slice.
func artifactsNewestFirst(artifacts types.MessageArtifacts) types.MessageArtifacts {
n := len(artifacts)
if n < 2 {
return artifacts
}
out := make(types.MessageArtifacts, n)
for i, artifact := range artifacts {
out[n-1-i] = artifact
}
return out
}
// mergeArtifactLists concatenates artifact lists in order, keeping the first
// occurrence of each storage URL. Order is preserved because a reference
// resolves to an index into the resulting list, so the caller's ordering
// decides which version a name points at: putting this turn's artifacts first
// makes a regenerated file shadow the older one.
func mergeArtifactLists(lists ...types.MessageArtifacts) types.MessageArtifacts {
var out types.MessageArtifacts
var seen map[string]struct{}
for _, list := range lists {
for _, artifact := range list {
key := strings.TrimSpace(artifact.URL)
if key != "" {
if _, exists := seen[key]; exists {
continue
}
if seen == nil {
seen = make(map[string]struct{})
}
seen[key] = struct{}{}
}
out = append(out, artifact)
}
}
return out
}
// historyOnlyArtifacts returns the entries of referenced that this turn did not
// produce. Those are the ones whose ownership has to be extended to the new
// message; the collector already bound the ones it persisted itself.
func historyOnlyArtifacts(referenced, current types.MessageArtifacts) types.MessageArtifacts {
if len(referenced) == 0 {
return nil
}
produced := make(map[string]struct{}, len(current))
for _, artifact := range current {
produced[strings.TrimSpace(artifact.URL)] = struct{}{}
}
var out types.MessageArtifacts
for _, artifact := range referenced {
if _, isCurrent := produced[strings.TrimSpace(artifact.URL)]; isCurrent {
continue
}
out = append(out, artifact)
}
return out
}
@@ -0,0 +1,316 @@
package session
import (
"fmt"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
// handleFor builds a syntactically valid 22-character resource handle for
// artifact i, so tests exercise the same ParseResourcePath path as production.
func handleFor(i int) string {
base := fmt.Sprintf("art%d", i)
return base + strings.Repeat("x", types.ResourceHandleLength-len(base))
}
func refFor(i int) string {
return types.BuildResourcePath(handleFor(i))
}
// artifactsFixture builds artifacts whose storage URL is a catalog handle —
// the normal deployment. Use artifactsWithoutCatalog for the degraded case.
func artifactsFixture(names ...string) types.MessageArtifacts {
list := make(types.MessageArtifacts, 0, len(names))
for i, name := range names {
list = append(list, types.MessageArtifact{FileName: name, URL: refFor(i)})
}
return list
}
func artifactsWithoutCatalog(names ...string) types.MessageArtifacts {
list := make(types.MessageArtifacts, 0, len(names))
for _, name := range names {
list = append(list, types.MessageArtifact{FileName: name, URL: "local://7/exports/" + name})
}
return list
}
func TestRewriteArtifactReferences(t *testing.T) {
artifacts := artifactsFixture(
"市场画像评分_e7edba.html",
"concept_ranking.csv",
"trend.png",
"腾讯控股(00700) 成交量_838ccc.html",
)
cases := []struct {
name string
content string
want string
}{
{
name: "file name with spaces and parentheses",
content: "![成交量](sandbox:腾讯控股(00700) 成交量_838ccc.html)",
want: "![成交量](" + refFor(3) + ")",
},
{
name: "file name with spaces and parentheses, no prefix",
content: "![成交量](腾讯控股(00700) 成交量_838ccc.html)",
want: "![成交量](" + refFor(3) + ")",
},
{
name: "bare file name in image",
content: "![市场画像评分](市场画像评分_e7edba.html)",
want: "![市场画像评分](" + refFor(0) + ")",
},
{
name: "sandbox prefix",
content: "![评分](sandbox:市场画像评分_e7edba.html)",
want: "![评分](" + refFor(0) + ")",
},
{
name: "sandbox scheme with slashes",
content: "![评分](sandbox://trend.png)",
want: "![评分](" + refFor(2) + ")",
},
{
name: "directory prefix is dropped",
content: "[榜单](/workspace/output/concept_ranking.csv)",
want: "[榜单](" + refFor(1) + ")",
},
{
name: "percent-encoded name",
content: "![评分](%E5%B8%82%E5%9C%BA%E7%94%BB%E5%83%8F%E8%AF%84%E5%88%86_e7edba.html)",
want: "![评分](" + refFor(0) + ")",
},
{
name: "title is preserved",
content: `![评分](trend.png "走势")`,
want: `![评分](` + refFor(2) + ` "走势")`,
},
{
name: "ordinary link with a colliding name is not rewritten",
content: "见 [说明](trend.png)",
want: "见 [说明](trend.png)",
},
{
name: "sandbox-prefixed link is rewritten even when not an image",
content: "数据见 [表格](sandbox:concept_ranking.csv)",
want: "数据见 [表格](" + refFor(1) + ")",
},
{
name: "already-rewritten reference is left alone",
content: "![评分](" + refFor(0) + ")",
want: "![评分](" + refFor(0) + ")",
},
{
name: "prose parentheses are not link destinations",
content: "腾讯控股(00700) 的成交量见下图。",
want: "腾讯控股(00700) 的成交量见下图。",
},
{
name: "unknown file name untouched",
content: "![别的](missing.html)",
want: "![别的](missing.html)",
},
{
name: "http url untouched",
content: "![远程](https://example.com/trend.png)",
want: "![远程](https://example.com/trend.png)",
},
{
name: "knowledge base image untouched",
content: "![资源](resource://abcdefghijklmnopqrstuv)",
want: "![资源](resource://abcdefghijklmnopqrstuv)",
},
{
name: "fenced code untouched",
content: "```\n![评分](trend.png)\n```",
want: "```\n![评分](trend.png)\n```",
},
{
name: "inline code untouched",
content: "写成 `![评分](trend.png)` 即可",
want: "写成 `![评分](trend.png)` 即可",
},
{
name: "plain prose untouched",
content: "生成了 trend.png 和 concept_ranking.csv 两个文件。",
want: "生成了 trend.png 和 concept_ranking.csv 两个文件。",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := rewriteArtifactReferences(tc.content, artifacts); got != tc.want {
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, tc.want)
}
})
}
}
func TestRewriteArtifactReferencesMixedContent(t *testing.T) {
artifacts := artifactsFixture("chart.html", "data.csv")
content := "## 图表\n\n![图表](chart.html)\n\n数据见 [表格](sandbox:data.csv)," +
"外链 [文档](https://example.com/chart.html) 不受影响。"
want := "## 图表\n\n![图表](" + refFor(0) + ")\n\n数据见 [表格](" + refFor(1) + ")," +
"外链 [文档](https://example.com/chart.html) 不受影响。"
if got := rewriteArtifactReferences(content, artifacts); got != want {
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, want)
}
}
// A knowledge-base image and a skill artifact routinely appear in the same
// answer. Only the artifact is rebound; the existing reference must survive
// byte for byte, since it already is the canonical form.
func TestRewriteArtifactReferencesKeepsExistingResourceImages(t *testing.T) {
artifacts := artifactsFixture("chart.html")
kbImage := types.BuildResourcePath(strings.Repeat("Z", types.ResourceHandleLength))
content := "![检索图](" + kbImage + ")\n\n![图表](chart.html)"
want := "![检索图](" + kbImage + ")\n\n![图表](" + refFor(0) + ")"
if got := rewriteArtifactReferences(content, artifacts); got != want {
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, want)
}
}
// Without a resource catalog there is no durable handle, so references are
// normalized to the chat-only sandbox form rather than leaking a storage path.
func TestRewriteArtifactReferencesWithoutCatalog(t *testing.T) {
artifacts := artifactsWithoutCatalog("chart.html")
got := rewriteArtifactReferences("![图表](chart.html)", artifacts)
if want := "![图表](sandbox:chart.html)"; got != want {
t.Fatalf("rewriteArtifactReferences() = %q, want %q", got, want)
}
if strings.Contains(got, "local://") {
t.Fatalf("storage path leaked into content: %q", got)
}
}
func TestRewriteArtifactReferencesNoArtifacts(t *testing.T) {
content := "![图表](chart.html)"
if got := rewriteArtifactReferences(content, nil); got != content {
t.Fatalf("rewriteArtifactReferences() = %q, want unchanged", got)
}
}
func TestArtifactRefByNameKeepsFirstDuplicate(t *testing.T) {
byName := artifactRefByName(artifactsFixture("a.html", "a.html", "b.html"))
if byName["a.html"] != refFor(0) {
t.Fatalf("duplicate name resolved to %q, want %q", byName["a.html"], refFor(0))
}
if byName["b.html"] != refFor(2) {
t.Fatalf("b.html resolved to %q, want %q", byName["b.html"], refFor(2))
}
}
func TestReferencedArtifactsMatchesNamesAndHandles(t *testing.T) {
artifacts := artifactsFixture("report.pptx", "chart.html", "data.csv")
cases := []struct {
name string
content string
want types.MessageArtifacts
}{
{
name: "sandbox-prefixed name",
content: "已生成 ![报告](sandbox:report.pptx)",
want: types.MessageArtifacts{artifacts[0]},
},
{
name: "bare name in an image",
content: "![图表](chart.html)",
want: types.MessageArtifacts{artifacts[1]},
},
{
name: "output path in an ordinary link",
content: "[数据](./output/data.csv)",
want: types.MessageArtifacts{artifacts[2]},
},
{
name: "canonical handle",
content: "![报告](" + refFor(0) + ")",
want: types.MessageArtifacts{artifacts[0]},
},
{
name: "prose mention is not a reference",
content: "生成了 report.pptx 和 chart.html 两个文件。",
want: nil,
},
{
name: "bare name in an ordinary link is not a reference",
content: "见 [说明](report.pptx)",
want: nil,
},
{
name: "unknown name",
content: "![别的](missing.pptx)",
want: nil,
},
{
name: "code sample is not a reference",
content: "```\n![报告](sandbox:report.pptx)\n```",
want: nil,
},
{
// Go regexp.Split does not interleave the matched fences, so
// walking parts with i+=2 would skip the segment after the first
// fence and miss a real citation that rewrite still rewrites.
name: "reference after a code fence",
content: "![报告](sandbox:report.pptx)\n\n```\n![忽略](sandbox:chart.html)\n```\n\n![图表](sandbox:chart.html)",
want: types.MessageArtifacts{artifacts[0], artifacts[1]},
},
{
name: "multiple references keep candidate order",
content: "![数据](data.csv)\n\n![报告](sandbox:report.pptx)",
want: types.MessageArtifacts{artifacts[0], artifacts[2]},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, referencedArtifacts(tc.content, artifacts))
})
}
}
// A regenerated file shadows the older version of itself: the name resolves to
// the first candidate, while an explicit handle still reaches the old one.
func TestReferencedArtifactsPrefersTheFirstCandidate(t *testing.T) {
old := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(0)}
fresh := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(1)}
candidates := types.MessageArtifacts{fresh, old}
require.Equal(t, types.MessageArtifacts{fresh},
referencedArtifacts("![deck](sandbox:deck.pptx)", candidates))
require.Equal(t, types.MessageArtifacts{old},
referencedArtifacts("![deck]("+old.URL+")", candidates))
}
// KnownArtifacts is oldest-first. Reverse it before merging so a hash-skipped
// name binds the latest file; this turn still shadows that latest file.
func TestMergeArtifactListsPrefersThisTurnThenLatestKnown(t *testing.T) {
old := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(0)}
latest := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(1)}
fresh := types.MessageArtifact{FileName: "deck.pptx", URL: refFor(2)}
known := types.MessageArtifacts{old, latest}
require.Equal(t, types.MessageArtifacts{latest},
referencedArtifacts("![deck](sandbox:deck.pptx)",
mergeArtifactLists(nil, artifactsNewestFirst(known))))
require.Equal(t, types.MessageArtifacts{fresh},
referencedArtifacts("![deck](sandbox:deck.pptx)",
mergeArtifactLists(types.MessageArtifacts{fresh}, artifactsNewestFirst(known))))
}
func TestArtifactsNewestFirstDoesNotMutateInput(t *testing.T) {
in := artifactsFixture("a.html", "b.html")
got := artifactsNewestFirst(in)
require.Equal(t, "b.html", got[0].FileName)
require.Equal(t, "a.html", got[1].FileName)
require.Equal(t, "a.html", in[0].FileName)
}
@@ -0,0 +1,144 @@
package session
import (
"context"
filesvc "academy/internal/application/service/file"
"academy/internal/logger"
"academy/internal/storageurl"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// resolveArtifactFileService returns the file service that owns an artifact's
// bytes, plus a context scoped to the owning tenant.
//
// Artifacts are not always on the process-wide file service: a tenant can pin
// its workspace to its own storage backend, and the object then only exists
// there. Both reading and deleting an artifact have to go through the same
// resolution, which is why it lives here rather than inline in the download
// handler.
//
// ok is false when the owning tenant or its backend cannot be reached; callers
// treat that as "artifact unavailable" rather than falling back to the default
// service, which would look in the wrong bucket.
func (h *Handler) resolveArtifactFileService(
ctx context.Context, ownerTenantID uint64, path, storageBackendID, label string,
) (interfaces.FileService, context.Context, bool) {
ctx = types.WithExecutionTenant(ctx, ownerTenantID)
if h.fileService == nil {
return nil, ctx, false
}
if h.tenantService == nil {
return h.fileService, ctx, true
}
tenant, err := h.tenantService.GetTenantByID(ctx, ownerTenantID)
if err != nil || tenant == nil {
return nil, ctx, false
}
backendID, providerPath, scoped := types.ParseStorageBackendPath(path)
if !scoped {
providerPath = path
}
if storageBackendID != "" {
backendID = storageBackendID
}
fileService, _, ok := filesvc.ResolveTenantFileServiceWithFallback(
ctx,
label,
tenant,
backendID,
types.ParseProviderScheme(providerPath),
storageurl.LocalStorageBaseDir(),
h.storageResolver,
h.fileService,
)
if !ok {
return nil, ctx, false
}
return fileService, ctx, true
}
// reclaimArtifactBlobs deletes the stored objects behind artifacts that were
// just tombstoned. Best-effort by design: the rows are already marked, and a
// blob left behind is recoverable (the tombstone still carries its url) while a
// failed request after a successful tombstone is not.
//
// A blob is only removed once the owning message's claim on it was the last
// one. An answer saved into a knowledge base, or a later turn that re-attached
// the same file, holds its own binding; deleting the bytes underneath it would
// break a document nobody asked to delete.
func (h *Handler) reclaimArtifactBlobs(ctx context.Context, tenantID uint64, refs []types.ArtifactBlobRef) {
for _, ref := range refs {
if ref.URL == "" {
continue
}
path, ownerTenantID, backendID, ok := h.locateArtifactBlob(ctx, tenantID, ref)
if !ok {
continue
}
fileService, blobCtx, ok := h.resolveArtifactFileService(
ctx, ownerTenantID, path, backendID, "artifact delete",
)
if !ok {
logger.Warnf(ctx, "artifact delete: storage unavailable for %s, blob kept", ref.URL)
continue
}
// DeleteFile takes the stored reference: the catalog-backed service
// resolves it and marks the resource deleted once the bytes are gone.
if err := fileService.DeleteFile(blobCtx, ref.URL); err != nil {
logger.Warnf(ctx, "artifact delete: failed to remove blob %s: %v", ref.URL, err)
}
}
}
// locateArtifactBlob drops every deleted message's claim on a blob and, when
// nothing is left holding it, reports where the bytes live. ok is false
// whenever the blob must be kept — another owner still references it, or a
// release failed and we cannot tell.
//
// An unreadable binding count keeps the file, matching the knowledge-delete
// path: an orphaned blob is reclaimable later, a file that vanished from
// someone else's document is not.
func (h *Handler) locateArtifactBlob(
ctx context.Context, tenantID uint64, ref types.ArtifactBlobRef,
) (path string, ownerTenantID uint64, backendID string, ok bool) {
if h.resourceCatalog == nil {
// No catalog: the url is a provider path in the caller's own tenant and
// nothing else can be holding a reference to it.
return ref.URL, tenantID, "", true
}
// -1 means the reference is not a catalog handle, i.e. there are no claims
// to account for; only a non-negative count is a real answer.
remaining := int64(-1)
for _, messageID := range ref.MessageIDs {
count, err := h.resourceCatalog.Release(ctx, ref.URL, types.ResourceOwnerMessage, messageID)
if err != nil {
logger.Warnf(ctx, "artifact delete: failed to release %s, blob kept: %v", ref.URL, err)
return "", 0, "", false
}
if count >= 0 {
remaining = count
}
}
if remaining > 0 {
logger.Infof(ctx, "artifact delete: keeping %s, %d owner(s) still reference it", ref.URL, remaining)
return "", 0, "", false
}
resolved, resource, err := h.resourceCatalog.ResolvePath(ctx, ref.URL)
if err != nil {
logger.Warnf(ctx, "artifact delete: failed to resolve %s, blob kept: %v", ref.URL, err)
return "", 0, "", false
}
if resource == nil {
return resolved, tenantID, "", true
}
if resource.TenantID != tenantID {
// The session is the caller's, so its artifacts should be too. A
// mismatch means the url points somewhere unexpected; leave it alone.
logger.Warnf(ctx, "artifact delete: %s belongs to tenant %d, not %d; blob kept",
ref.URL, resource.TenantID, tenantID)
return "", 0, "", false
}
return resolved, resource.TenantID, resource.StorageBackendID, true
}
@@ -0,0 +1,364 @@
package session
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"fmt"
"path/filepath"
"strings"
"academy/internal/common"
"academy/internal/infrastructure/docparser"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/google/uuid"
)
const (
// maxTextFileLines is the line limit for inline text content; excess lines are truncated.
maxTextFileLines = 500
// textFileExtensions lists plain-text extensions handled by the line-based reader.
textFileExtensions = ".txt,.md,.markdown,.json,.xml,.yaml,.yml,.csv,.log"
)
// AttachmentProcessor saves uploaded file attachments and extracts their text content
// for injection into the LLM prompt.
type AttachmentProcessor struct {
fileService interfaces.FileService
documentReader interfaces.DocumentReader
imageResolver *docparser.ImageResolver
modelService interfaces.ModelService // used to obtain the ASR model
}
// NewAttachmentProcessor creates an AttachmentProcessor with the given dependencies.
func NewAttachmentProcessor(
fileService interfaces.FileService,
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
modelService interfaces.ModelService,
) *AttachmentProcessor {
return &AttachmentProcessor{
fileService: fileService,
documentReader: documentReader,
imageResolver: imageResolver,
modelService: modelService,
}
}
// ProcessAttachment validates, saves, and extracts content from a single uploaded file.
// Content extraction is attempted for all supported types; errors are non-fatal (logged as warnings).
func (p *AttachmentProcessor) ProcessAttachment(
ctx context.Context,
data []byte,
fileName string,
fileSize int64,
tenantID uint64,
asrModelID string, // optional; enables audio transcription when set
) (*types.MessageAttachment, error) {
logger.Infof(ctx, "processing attachment: fileName=%s, fileSize=%d", secutils.SanitizeForLog(fileName), fileSize)
// Validate filename (injection / path-traversal checks)
safeFileName, isValid := secutils.ValidateInput(fileName)
if !isValid {
return nil, fmt.Errorf("invalid characters in file name")
}
baseName, err := secutils.SafeFileName(safeFileName)
if err != nil {
return nil, fmt.Errorf("unsafe file name: %w", err)
}
ext := strings.ToLower(filepath.Ext(baseName))
if ext == "" {
ext = ".txt"
}
if !isValidFileType(baseName) {
return nil, fmt.Errorf("unsupported file type: %s", ext)
}
uniqueFileName := fmt.Sprintf("attachment_%s%s", uuid.New().String()[:12], ext)
storageURL, err := p.fileService.SaveBytes(ctx, data, tenantID, uniqueFileName, false)
if err != nil {
return nil, fmt.Errorf("failed to save attachment: %w", err)
}
attachment := &types.MessageAttachment{
URL: storageURL,
FileName: baseName,
FileType: ext,
FileSize: fileSize,
}
// Extract text content based on file type; errors are non-fatal.
if p.isTextFile(ext) {
if err := p.processTextFile(ctx, data, attachment); err != nil {
logger.Warnf(ctx, "text file processing failed: %v", err)
attachment.Content = fmt.Sprintf("<error><message>Failed to process text file</message><details>%v</details></error>", err)
}
} else if docparser.IsAudioFormat(ext) {
if err := p.processAudioFile(ctx, data, baseName, attachment, asrModelID); err != nil {
logger.Warnf(ctx, "audio transcription failed: %v, keeping placeholder", err)
attachment.Content = fmt.Sprintf("<error><message>Failed to transcribe audio file</message><details>%v</details></error>", err)
}
} else if docparser.IsSimpleFormat(ext) {
if err := p.processWithDocParser(ctx, data, baseName, ext, attachment, tenantID); err != nil {
logger.Warnf(ctx, "SimpleFormatReader failed: %v", err)
attachment.Content = fmt.Sprintf("<error><message>Failed to parse document</message><details>%v</details></error>", err)
}
} else {
if err := p.processWithDocumentReader(ctx, data, baseName, ext, attachment, tenantID); err != nil {
logger.Warnf(ctx, "DocumentReader failed: %v, keeping metadata only", err)
attachment.Content = fmt.Sprintf("<error><message>Failed to read document</message><details>%v</details></error>", err)
}
}
attachment.Content = common.CleanInvalidUTF8(attachment.Content)
logger.Infof(ctx, "attachment processed: fileName=%s, truncated=%v, contentLen=%d",
secutils.SanitizeForLog(baseName), attachment.IsTruncated, len(attachment.Content))
return attachment, nil
}
// isTextFile reports whether ext is a plain-text extension handled line-by-line.
func (p *AttachmentProcessor) isTextFile(ext string) bool {
return strings.Contains(textFileExtensions, ext)
}
// processTextFile reads plain-text content line by line, truncating at maxTextFileLines.
func (p *AttachmentProcessor) processTextFile(ctx context.Context, data []byte, attachment *types.MessageAttachment) error {
scanner := bufio.NewScanner(bytes.NewReader(data))
var lines []string
lineCount := 0
for scanner.Scan() {
lineCount++
if lineCount <= maxTextFileLines {
lines = append(lines, scanner.Text())
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("failed to read file content: %w", err)
}
attachment.LineCount = lineCount
attachment.Content = strings.Join(lines, "\n")
if lineCount > maxTextFileLines {
attachment.IsTruncated = true
logger.Infof(ctx, "text file truncated: total=%d, kept=%d", lineCount, maxTextFileLines)
}
return nil
}
// processWithDocParser extracts content via SimpleFormatReader (md, csv, json, images, etc.).
func (p *AttachmentProcessor) processWithDocParser(
ctx context.Context,
data []byte,
fileName string,
fileType string,
attachment *types.MessageAttachment,
tenantID uint64,
) error {
reader := &docparser.SimpleFormatReader{}
result, err := reader.Read(ctx, &types.ReadRequest{
FileContent: data,
FileName: fileName,
FileType: fileType,
})
if err != nil {
return fmt.Errorf("SimpleFormatReader failed: %w", err)
}
// Resolve embedded image refs to storage URLs.
if len(result.ImageRefs) > 0 && p.imageResolver != nil {
updatedMarkdown, _, err := p.imageResolver.ResolveAndStore(ctx, result, p.fileService, tenantID)
if err != nil {
logger.Warnf(ctx, "image resolution failed: %v", err)
} else {
result.MarkdownContent = updatedMarkdown
}
}
p.applyLineTruncation(ctx, result.MarkdownContent, attachment)
return nil
}
// processAudioFile transcribes audio via ASR. Falls back to a placeholder when no ASR model is configured.
func (p *AttachmentProcessor) processAudioFile(
ctx context.Context,
data []byte,
fileName string,
attachment *types.MessageAttachment,
asrModelID string,
) error {
if asrModelID == "" || p.modelService == nil {
attachment.Content = fmt.Sprintf("<audio_file name=\"%s\" transcription=\"unsupported\" />", fileName)
logger.Infof(ctx, "no ASR model configured, keeping audio placeholder")
return nil
}
asrInstance, err := p.modelService.GetASRModel(ctx, asrModelID)
if err != nil {
return fmt.Errorf("failed to get ASR model: %w", err)
}
logger.Infof(ctx, "starting audio transcription: fileName=%s, size=%d", fileName, len(data))
res, err := asrInstance.Transcribe(ctx, data, fileName)
if err != nil {
return fmt.Errorf("audio transcription failed: %w", err)
}
transcript := res.Text
p.applyLineTruncation(ctx, transcript, attachment)
logger.Infof(ctx, "audio transcription done: textLen=%d", len(transcript))
return nil
}
// processWithDocumentReader extracts content from complex formats (pdf, docx, xlsx, etc.).
func (p *AttachmentProcessor) processWithDocumentReader(
ctx context.Context,
data []byte,
fileName string,
fileType string,
attachment *types.MessageAttachment,
tenantID uint64,
) error {
if p.documentReader == nil {
return fmt.Errorf("DocumentReader not configured")
}
normalizedType := strings.TrimPrefix(fileType, ".")
parserEngine := ""
if v := ctx.Value(types.ChatParserEngineContextKey); v != nil {
if s, ok := v.(string); ok {
parserEngine = s
}
}
overrides := getParserEngineOverridesFromContext(ctx)
// Engines that parse in this process (anydoc, MinerU, ...) are resolved
// through the registry so a chat attachment honours the same engine rules
// as an ingested document. Anything the registry cannot build here — a
// cloud engine whose credentials this path cannot resolve — falls back to
// the docreader, which is where every engine name went before.
reader, err := docparser.NewReader(ctx, parserEngine, normalizedType, false, docparser.ReaderDeps{
Overrides: overrides,
Remote: p.documentReader,
})
if err != nil {
logger.Warnf(ctx, "parser engine %q unusable for this attachment, using docreader: %v", parserEngine, err)
reader = p.documentReader
}
result, err := reader.Read(ctx, &types.ReadRequest{
FileContent: data,
FileName: fileName,
FileType: normalizedType,
ParserEngine: parserEngine,
ParserEngineOverrides: overrides,
})
if err != nil {
return fmt.Errorf("document parsing failed: %w", err)
}
// Resolve embedded image refs to storage URLs.
if len(result.ImageRefs) > 0 && p.imageResolver != nil {
updatedMarkdown, _, err := p.imageResolver.ResolveAndStore(ctx, result, p.fileService, tenantID)
if err != nil {
logger.Warnf(ctx, "image resolution failed: %v", err)
} else {
result.MarkdownContent = updatedMarkdown
}
}
p.applyLineTruncation(ctx, result.MarkdownContent, attachment)
return nil
}
// applyLineTruncation stores content into attachment, truncating at maxTextFileLines if needed.
func (p *AttachmentProcessor) applyLineTruncation(ctx context.Context, content string, attachment *types.MessageAttachment) {
lines := strings.Split(content, "\n")
lineCount := len(lines)
attachment.LineCount = lineCount
if lineCount > maxTextFileLines {
attachment.Content = strings.Join(lines[:maxTextFileLines], "\n")
attachment.IsTruncated = true
logger.Infof(ctx, "content truncated: total=%d, kept=%d", lineCount, maxTextFileLines)
} else {
attachment.Content = content
}
}
// isValidFileType reports whether fileName has a supported extension.
// Kept in sync with the frontend SUPPORTED_TYPES list in AttachmentUpload.vue.
func isValidFileType(fileName string) bool {
ext := strings.ToLower(filepath.Ext(fileName))
if ext == "" {
return false
}
ext = strings.TrimPrefix(ext, ".")
supportedTypes := []string{
// documents
"docx", "doc", "pdf", "ppt", "pptx", "epub", "mhtml",
// spreadsheets
"xlsx", "xls",
// text / markup
"md", "markdown", "txt", "csv", "json", "xml", "yaml", "yml", "log", "html",
// images
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "webp",
// audio
"mp3", "wav", "m4a", "flac", "ogg", "aac",
}
for _, t := range supportedTypes {
if ext == t {
return true
}
}
return false
}
// getParserEngineOverridesFromContext returns parser engine overrides from tenant in context.
func getParserEngineOverridesFromContext(ctx context.Context) map[string]string {
if v := ctx.Value(types.TenantInfoContextKey); v != nil {
if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.ParserEngineConfig != nil {
return tenant.ParserEngineConfig.ToOverridesMap()
}
}
return nil
}
// DecodeBase64Attachment decodes a base64 attachment payload, stripping any data URI prefix.
// Tries Std, URL, RawStd, and RawURL encodings in order.
func DecodeBase64Attachment(data string) ([]byte, error) {
// Strip data URI prefix (e.g. "data:application/pdf;base64,")
if idx := strings.Index(data, ","); idx != -1 {
data = data[idx+1:]
}
data = strings.TrimSpace(data)
for _, enc := range []struct{ e *base64.Encoding }{
{base64.StdEncoding},
{base64.URLEncoding},
{base64.RawStdEncoding},
{base64.RawURLEncoding},
} {
if decoded, err := enc.e.DecodeString(data); err == nil {
return decoded, nil
}
}
return nil, fmt.Errorf("base64 decode failed: unrecognised encoding")
}
@@ -0,0 +1,45 @@
package session
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type automationConversationStub struct{ interfaces.SessionService }
func (*automationConversationStub) GetOwnedSession(_ context.Context, id string) (*types.Session, error) {
return &types.Session{ID: id, Kind: types.SessionKindAutomation}, nil
}
func TestAutomationConversationRejectsManualMessages(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{sessionService: &automationConversationStub{}}
r := gin.New()
r.Use(middleware.ErrorHandler())
r.POST("/knowledge-chat/:session_id", h.KnowledgeQA)
r.POST("/agent-chat/:session_id", h.AgentQA)
r.POST("/sessions/:session_id/steer", h.SteerMessage)
r.POST("/sessions/:session_id/steer/:steer_id/inject", h.PromoteSteerMessage)
for _, path := range []string{
"/knowledge-chat/session", "/agent-chat/session",
"/sessions/session/steer", "/sessions/session/steer/queued/inject",
} {
t.Run(path, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"query":"manual message"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusForbidden, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), "automation conversations")
})
}
}
+66
View File
@@ -0,0 +1,66 @@
package session
import (
"context"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// ackBackgroundNotices acknowledges the background notices a persisted
// assistant message carries: the ones injected into its turn and the ones its
// work tools returned. Until the message is saved they stay in the inbox, so a
// turn that never reached history delivers them again next run. ctx carries
// the session's tenant, as on every completeAssistantMessage path.
func (h *Handler) ackBackgroundNotices(ctx context.Context, msg *types.Message) {
if h.background == nil || h.background.Inbox == nil || msg == nil {
return
}
ids := backgroundNoticeIDs(msg.AgentSteps)
if len(ids) == 0 {
return
}
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok || tenantID == 0 {
return
}
ref := interfaces.SessionRef{TenantID: tenantID, SessionID: msg.SessionID}
if err := h.background.Inbox.Ack(ctx, ref, ids); err != nil {
logger.Warnf(ctx, "ack background notices for message %s failed: %v", msg.ID, err)
}
}
// backgroundNoticeIDs collects every notice ID the steps delivered or showed,
// once each, in order.
func backgroundNoticeIDs(steps []types.AgentStep) []string {
var ids []string
seen := make(map[string]bool)
add := func(id string) {
if id != "" && !seen[id] {
seen[id] = true
ids = append(ids, id)
}
}
for _, step := range steps {
for _, injection := range step.BackgroundInjections {
for _, id := range injection.AckIDs {
add(id)
}
}
for _, id := range step.BackgroundSeenIDs {
add(id)
}
}
return ids
}
// notifyBackgroundStop tells background features the user stopped the turn.
// Each feature decides what that means for its own work.
func (h *Handler) notifyBackgroundStop(ctx context.Context, session *types.Session) {
if h.background == nil || h.background.Listeners == nil || session == nil {
return
}
h.background.Listeners.NotifyStop(context.WithoutCancel(ctx),
interfaces.SessionRef{TenantID: session.TenantID, SessionID: session.ID})
}
+230
View File
@@ -0,0 +1,230 @@
package session
import (
"context"
"net/http"
"time"
"academy/internal/application/service"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type backgroundWorkItem struct {
WorkID string `json:"work_id"`
Kind string `json:"kind"`
Title string `json:"title"`
State string `json:"state"`
StartedAt string `json:"started_at,omitempty"`
FinishedAt string `json:"finished_at,omitempty"`
ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
}
// ListBackgroundWork returns the session's background items: live ones from the
// activity registry plus notices finished within the last 24h. Terminal states
// come from Handler.Status with Detailed false. Nothing here execs a sandbox.
func (h *Handler) ListBackgroundWork(c *gin.Context) {
sessionID := paramSessionID(c)
ctx := c.Request.Context()
session, err := h.sessionService.GetSession(ctx, sessionID)
if err != nil || session == nil {
writeNotFound(c, "session not found")
return
}
items := make([]backgroundWorkItem, 0)
if h.background == nil || !h.background.Enabled() {
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
return
}
ref := sessionWorkRef(session)
live, err := h.background.Registry.List(ctx, ref)
if err != nil {
logger.Warnf(ctx, "list background work session=%s: %v", sessionID, err)
writeUnavailable(c, "background work is temporarily unavailable")
return
}
liveSet := make(map[string]struct{}, len(live))
for _, activity := range live {
liveSet[activity.ID] = struct{}{}
items = append(items, backgroundWorkItem{
WorkID: activity.ID,
Kind: activity.Kind,
Title: activity.Title,
State: interfaces.WorkStateRunning,
StartedAt: formatWorkTime(activity.StartedAt),
})
}
notices, err := h.background.Inbox.Pending(ctx, ref)
if err != nil {
logger.Warnf(ctx, "pending background notices session=%s: %v", sessionID, err)
writeUnavailable(c, "background work is temporarily unavailable")
return
}
terminalIDs := make([]string, 0, len(notices))
for _, notice := range notices {
if _, ok := liveSet[notice.ID]; ok || notice.ID == "" {
continue
}
terminalIDs = append(terminalIDs, notice.ID)
}
resolved := h.terminalWorkResults(ctx, ref, terminalIDs)
for _, notice := range notices {
if _, ok := liveSet[notice.ID]; ok {
continue
}
result, ok := resolved[notice.ID]
state, title := terminalWorkView(notice, result, ok)
items = append(items, backgroundWorkItem{
WorkID: notice.ID,
Kind: notice.Kind,
Title: title,
State: state,
FinishedAt: formatWorkTime(notice.FinishedAt),
})
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// GetBackgroundWork returns one item's detail with output. RunID stays empty:
// a user-triggered read must not move the model's incremental cursor.
func (h *Handler) GetBackgroundWork(c *gin.Context) {
sessionID := paramSessionID(c)
workID := c.Param("work_id")
ctx := c.Request.Context()
session, err := h.sessionService.GetSession(ctx, sessionID)
if err != nil || session == nil {
writeNotFound(c, "session not found")
return
}
if h.background == nil || !h.background.Enabled() {
writeNotFound(c, "background work is not available")
return
}
ref := sessionWorkRef(session)
results, err := h.background.Handler.Status(ctx, ref, []string{workID}, interfaces.StatusOptions{
Detailed: true,
RunID: "",
})
if err != nil || len(results) != 1 {
writeNotFound(c, "background work not found")
return
}
id := results[0].ID
if id == "" {
id = workID
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"work_id": id,
"state": results[0].State,
"title": results[0].Title,
"result": results[0].Payload,
}})
}
// CancelBackgroundWork stops one item. Strictly owner-only: mutations must not
// honour admin read access (same GetOwnedSession rule as steer).
func (h *Handler) CancelBackgroundWork(c *gin.Context) {
sessionID := paramSessionID(c)
workID := c.Param("work_id")
ctx := c.Request.Context()
session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
if err != nil || session == nil {
writeNotFound(c, "session not found")
return
}
if h.background == nil || !h.background.Enabled() {
writeNotFound(c, "background work is not available")
return
}
ref := sessionWorkRef(session)
results, err := h.background.Handler.Cancel(ctx, ref, []string{workID})
if err != nil || len(results) != 1 {
writeNotFound(c, "background work not found")
return
}
id := results[0].ID
if id == "" {
id = workID
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"work_id": id,
"state": results[0].State,
}})
}
func sessionWorkRef(session *types.Session) interfaces.SessionRef {
return interfaces.SessionRef{TenantID: session.TenantID, SessionID: session.ID}
}
func (h *Handler) terminalWorkResults(
ctx context.Context, ref interfaces.SessionRef, ids []string,
) map[string]interfaces.WorkResult {
out := make(map[string]interfaces.WorkResult, len(ids))
if len(ids) == 0 || h.background == nil || h.background.Handler == nil {
return out
}
results, err := h.background.Handler.Status(ctx, ref, ids, interfaces.StatusOptions{
Detailed: false,
RunID: "",
})
if err != nil {
logger.Warnf(ctx, "background work status session=%s: %v", ref.SessionID, err)
return out
}
for _, result := range results {
out[result.ID] = result
}
return out
}
func terminalWorkView(
notice interfaces.BackgroundNotice, result interfaces.WorkResult, ok bool,
) (string, string) {
if ok && result.State != "" && result.State != interfaces.WorkStateUnknown {
return result.State, result.Title
}
if parsed := service.ParseShellJobNoticeState(notice.Text); parsed != "" {
if ok {
return parsed, result.Title
}
return parsed, ""
}
if ok {
return interfaces.WorkStateLost, result.Title
}
return interfaces.WorkStateLost, ""
}
func formatWorkTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
// writeNotFound returns HTTP 404 itself. Session routes in production also
// install ErrorHandler, which only writes when c.Errors is set; writing here
// keeps a router that has no error middleware on the same status.
func writeNotFound(c *gin.Context, message string) {
writeAppError(c, errors.NewNotFoundError(message))
}
// writeUnavailable is a retryable failure. An empty 200 would clear the chip
// and stop the client's poll, while the jobs are still running.
func writeUnavailable(c *gin.Context, message string) {
writeAppError(c, errors.NewServiceUnavailableError(message))
}
func writeAppError(c *gin.Context, appErr *errors.AppError) {
c.AbortWithStatusJSON(appErr.HTTPCode, gin.H{
"success": false,
"error": gin.H{
"code": appErr.Code,
"message": appErr.Message,
"details": appErr.Details,
},
})
}
@@ -0,0 +1,253 @@
package session
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"academy/internal/application/service"
"academy/internal/background"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type httpWorkHandler struct {
interfaces.WorkHandler
status map[string]interfaces.WorkResult
cancel []string
refs []interfaces.SessionRef
opts []interfaces.StatusOptions
}
func (h *httpWorkHandler) Status(_ context.Context, ref interfaces.SessionRef,
ids []string, opts interfaces.StatusOptions,
) ([]interfaces.WorkResult, error) {
h.refs = append(h.refs, ref)
h.opts = append(h.opts, opts)
out := make([]interfaces.WorkResult, 0, len(ids))
for _, id := range ids {
if r, ok := h.status[id]; ok {
out = append(out, r)
continue
}
// A live id is not in the terminal map. Detail still has to resolve.
out = append(out, interfaces.WorkResult{ID: id, State: interfaces.WorkStateRunning})
}
return out, nil
}
func (h *httpWorkHandler) Cancel(
_ context.Context, ref interfaces.SessionRef, ids []string,
) ([]interfaces.WorkResult, error) {
h.refs = append(h.refs, ref)
h.cancel = append(h.cancel, ids...)
out := make([]interfaces.WorkResult, 0, len(ids))
for _, id := range ids {
out = append(out, interfaces.WorkResult{ID: id, State: interfaces.WorkStateCancelled, Terminal: true})
}
return out, nil
}
func (s *stubSessionService) GetOwnedSession(ctx context.Context, id string) (*types.Session, error) {
session, err := s.GetSession(ctx, id)
if err != nil || session == nil {
if err == nil {
err = errors.New("session not found")
}
return nil, err
}
// Strict owner: a caller executing as another tenant must not mutate.
if tenant, ok := types.TenantIDFromContext(ctx); ok && tenant != session.TenantID {
return nil, errors.New("session not found")
}
return session, nil
}
func newBackgroundHTTPRouter(t *testing.T, work *service.BackgroundWork,
sessionSvc interfaces.SessionService,
) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
h := &Handler{background: work, sessionService: sessionSvc}
r := gin.New()
r.GET("/api/v1/sessions/:id/background-work", h.ListBackgroundWork)
r.GET("/api/v1/sessions/:id/background-work/:work_id", h.GetBackgroundWork)
r.POST("/api/v1/sessions/:session_id/background-work/:work_id/cancel", h.CancelBackgroundWork)
return r
}
func ownedSessionContext(t *testing.T, tenant uint64, sessionID string) context.Context {
t.Helper()
ctx := types.WithExecutionTenant(context.Background(), tenant)
ctx = types.WithSandboxTenantID(ctx, tenant)
return types.WithSessionID(ctx, sessionID)
}
// splitCallerContext is a read whose execution tenant and sandbox-pin tenant
// both differ from the session row. The handler must still use session.TenantID.
func splitCallerContext(t *testing.T, sessionID string) context.Context {
t.Helper()
ctx := types.WithExecutionTenant(context.Background(), 99)
ctx = types.WithSandboxTenantID(ctx, 100)
return types.WithSessionID(ctx, sessionID)
}
func TestListMergesRegistryAndInboxWithoutExec(t *testing.T) {
ref := interfaces.SessionRef{TenantID: 7, SessionID: "s"}
work := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
handler := &httpWorkHandler{status: map[string]interfaces.WorkResult{
"sj_ab01": {
ID: "sj_ab01", State: interfaces.WorkStateSucceeded, Terminal: true, Title: "build",
},
}}
work.Handler = handler
err := work.Registry.Add(context.Background(), ref,
interfaces.BackgroundActivity{ID: "sj_0123", Kind: "shell", Title: "tests"}, time.Minute, 0)
require.NoError(t, err)
finished := time.Now().UTC()
_, err = work.Inbox.Push(context.Background(), ref, interfaces.BackgroundNotice{
ID: "sj_ab01", Kind: "shell", Text: "Background shell sj_ab01 succeeded: build.",
FinishedAt: finished,
})
require.NoError(t, err)
r := newBackgroundHTTPRouter(t, work, &stubSessionService{session: &types.Session{ID: "s", TenantID: 7}})
req := httptest.NewRequest(http.MethodGet, "/api/v1/sessions/s/background-work", nil).
WithContext(splitCallerContext(t, "s"))
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var body struct {
Data []map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
require.Len(t, body.Data, 2, "运行中(登记表)+ 24h 内终态(信箱)")
states := map[string]any{}
titles := map[string]any{}
for _, item := range body.Data {
states[item["work_id"].(string)] = item["state"]
titles[item["work_id"].(string)] = item["title"]
}
require.Equal(t, "running", states["sj_0123"])
require.Equal(t, "succeeded", states["sj_ab01"])
require.Equal(t, "tests", titles["sj_0123"])
require.Equal(t, "build", titles["sj_ab01"])
require.NotEmpty(t, handler.opts, "终态 state 由 Status(Detailed=false) 批量补齐")
for _, opts := range handler.opts {
require.False(t, opts.Detailed)
require.Empty(t, opts.RunID)
}
require.NotEmpty(t, handler.refs)
for _, got := range handler.refs {
require.Equal(t, uint64(7), got.TenantID)
require.Equal(t, "s", got.SessionID)
}
}
func TestDetailAndCancelEnforceOwnership(t *testing.T) {
work := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
handler := &httpWorkHandler{status: map[string]interfaces.WorkResult{}}
work.Handler = handler
svc := &stubSessionService{session: &types.Session{ID: "s", TenantID: 7}}
r := newBackgroundHTTPRouter(t, work, svc)
// Owner read goes through GetSession. Caller tenant and sandbox pin differ
// from the session row; the status ref must still be the session tenant.
req := httptest.NewRequest(http.MethodGet,
"/api/v1/sessions/s/background-work/sj_0123", nil).
WithContext(splitCallerContext(t, "s"))
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), `"state":"running"`)
require.NotEmpty(t, handler.opts)
last := handler.opts[len(handler.opts)-1]
require.True(t, last.Detailed)
require.Empty(t, last.RunID, "a user read must not move the model cursor")
require.Equal(t, interfaces.SessionRef{TenantID: 7, SessionID: "s"}, handler.refs[len(handler.refs)-1])
// 取消走严格 owner(stub 拒绝非 owner)
req = httptest.NewRequest(http.MethodPost,
"/api/v1/sessions/s/background-work/sj_0123/cancel", nil).
WithContext(ownedSessionContext(t, 8, "s"))
rec = httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusNotFound, rec.Code, "GetOwnedSession 失败 → 404,不区分 403 防探测")
require.Empty(t, handler.cancel)
}
type errActivityRegistry struct {
interfaces.ActivityRegistry
}
func (errActivityRegistry) List(context.Context, interfaces.SessionRef) ([]interfaces.BackgroundActivity, error) {
return nil, errors.New("redis down")
}
func TestListStorageErrorIsNotAnEmptySuccess(t *testing.T) {
work := service.NewBackgroundWork(errActivityRegistry{}, background.NewMemoryNoticeInbox(nil))
work.Handler = &httpWorkHandler{}
r := newBackgroundHTTPRouter(t, work, &stubSessionService{session: &types.Session{ID: "s", TenantID: 7}})
req := httptest.NewRequest(http.MethodGet, "/api/v1/sessions/s/background-work", nil).
WithContext(ownedSessionContext(t, 7, "s"))
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.GreaterOrEqual(t, rec.Code, 500)
require.NotContains(t, rec.Body.String(), `"data":[]`)
}
func TestDisabledBackgroundWorkIsEmptyListAnd404(t *testing.T) {
sessionSvc := &stubSessionService{session: &types.Session{ID: "s", TenantID: 7}}
r := newBackgroundHTTPRouter(t, nil, sessionSvc)
req := httptest.NewRequest(http.MethodGet, "/api/v1/sessions/s/background-work", nil).
WithContext(ownedSessionContext(t, 7, "s"))
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), `"data":[]`)
req = httptest.NewRequest(http.MethodGet,
"/api/v1/sessions/s/background-work/sj_0123", nil).
WithContext(ownedSessionContext(t, 7, "s"))
rec = httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusNotFound, rec.Code)
req = httptest.NewRequest(http.MethodPost,
"/api/v1/sessions/s/background-work/sj_0123/cancel", nil).
WithContext(ownedSessionContext(t, 7, "s"))
rec = httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusNotFound, rec.Code)
// Enabled() is false until Handler, Registry, and Inbox are all set.
// Rows already stored must not leak through a disabled bundle.
work := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
ref := interfaces.SessionRef{TenantID: 7, SessionID: "s"}
err := work.Registry.Add(context.Background(), ref,
interfaces.BackgroundActivity{ID: "sj_0123", Kind: "shell", Title: "tests"}, time.Minute, 0)
require.NoError(t, err)
_, err = work.Inbox.Push(context.Background(), ref, interfaces.BackgroundNotice{
ID: "sj_ab01", Kind: "shell", Text: "Background shell sj_ab01 succeeded: build.",
FinishedAt: time.Now().UTC(),
})
require.NoError(t, err)
require.False(t, work.Enabled())
r = newBackgroundHTTPRouter(t, work, sessionSvc)
req = httptest.NewRequest(http.MethodGet, "/api/v1/sessions/s/background-work", nil).
WithContext(ownedSessionContext(t, 7, "s"))
rec = httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), `"data":[]`)
req = httptest.NewRequest(http.MethodGet,
"/api/v1/sessions/s/background-work/sj_0123", nil).
WithContext(ownedSessionContext(t, 7, "s"))
rec = httptest.NewRecorder()
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusNotFound, rec.Code)
}
@@ -0,0 +1,96 @@
package session
import (
"context"
"errors"
"testing"
"time"
"academy/internal/application/service"
"academy/internal/background"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type recordingSessionListener struct {
stopped []interfaces.SessionRef
}
func (l *recordingSessionListener) OnStop(_ context.Context, s interfaces.SessionRef) error {
l.stopped = append(l.stopped, s)
return nil
}
func (l *recordingSessionListener) OnDelete(context.Context, interfaces.SessionRef) error { return nil }
func newAckFixture(t *testing.T) (*service.BackgroundWork, interfaces.SessionRef) {
t.Helper()
work := service.NewBackgroundWork(background.NewMemoryActivityRegistry(nil), background.NewMemoryNoticeInbox(nil))
ref := interfaces.SessionRef{TenantID: 1, SessionID: "s"}
for _, id := range []string{"sj_1", "sj_2", "sj_3"} {
_, err := work.Inbox.Push(context.Background(), ref, interfaces.BackgroundNotice{
ID: id, Kind: "shell_job", Text: id, FinishedAt: time.Now(),
})
require.NoError(t, err)
}
return work, ref
}
func messageCarryingNotices() *types.Message {
return &types.Message{
ID: "m", SessionID: "s", Role: "assistant", Content: "done",
AgentSteps: []types.AgentStep{
{BackgroundInjections: []types.BackgroundInjection{{Content: "x", AckIDs: []string{"sj_1"}}}},
{BackgroundSeenIDs: []string{"sj_2", "sj_1"}},
},
}
}
func pendingIDs(t *testing.T, work *service.BackgroundWork, ref interfaces.SessionRef) []string {
t.Helper()
notices, err := work.Inbox.Pending(context.Background(), ref)
require.NoError(t, err)
ids := make([]string, 0, len(notices))
for _, n := range notices {
ids = append(ids, n.ID)
}
return ids
}
func TestPersistedMessageAcknowledgesTheNoticesItCarries(t *testing.T) {
work, ref := newAckFixture(t)
h := &Handler{messageService: &imageCompletionMessages{}, background: work}
ctx := types.WithExecutionTenant(context.Background(), 1)
require.NoError(t, h.completeAssistantMessage(ctx, messageCarryingNotices(), "", ""))
require.ElementsMatch(t, []string{"sj_3"}, pendingIDs(t, work, ref))
}
func TestFailedPersistLeavesNoticesForTheNextRun(t *testing.T) {
work, ref := newAckFixture(t)
h := &Handler{messageService: &imageCompletionMessages{err: errors.New("db down")}, background: work}
ctx := types.WithExecutionTenant(context.Background(), 1)
require.Error(t, h.completeAssistantMessage(ctx, messageCarryingNotices(), "", ""))
require.ElementsMatch(t, []string{"sj_1", "sj_2", "sj_3"}, pendingIDs(t, work, ref))
}
func TestBackgroundNoticeIDsAreDeduplicatedInOrder(t *testing.T) {
require.Equal(t, []string{"sj_1", "sj_2"}, backgroundNoticeIDs(messageCarryingNotices().AgentSteps))
require.Empty(t, backgroundNoticeIDs(nil))
}
func TestStopNotifiesBackgroundListeners(t *testing.T) {
work := service.NewBackgroundWork(nil, nil)
listener := &recordingSessionListener{}
work.Listeners.Register(listener)
h := &Handler{background: work}
h.notifyBackgroundStop(context.Background(), &types.Session{ID: "s", TenantID: 3})
(&Handler{}).notifyBackgroundStop(context.Background(), &types.Session{ID: "s", TenantID: 3})
require.Equal(t, []interfaces.SessionRef{{TenantID: 3, SessionID: "s"}}, listener.stopped)
}
+271
View File
@@ -0,0 +1,271 @@
package session
import (
"context"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"academy/internal/browserskill"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
// pairingOrigin chooses the WebSocket host the extension will dial.
// A loopback API listener always wins, so a Lite page cannot point the
// extension at another host. A public page origin is kept only when its
// hostname is the request host; the port still comes from that page so a
// reverse proxy can preserve the external port.
func pairingOrigin(r *http.Request, page string) string {
host := ""
if r != nil {
host = r.Host
}
if isLoopbackHostname(requestHostname(host)) {
if origin, ok := loopbackPairingOrigin(host); ok {
return origin
}
return ""
}
if origin, ok := pageOriginMatchingHost(page, host); ok {
return origin
}
if isHTTPOrigin(page) {
if origin := requestHTTPOrigin(r); origin != "" {
return origin
}
}
return page
}
func requestHostname(host string) string {
if parsed, _, err := net.SplitHostPort(host); err == nil {
return parsed
}
return host
}
func isLoopbackHostname(hostname string) bool {
switch strings.ToLower(hostname) {
case "localhost", "127.0.0.1", "::1":
return true
default:
return false
}
}
func loopbackPairingOrigin(host string) (string, bool) {
host = strings.TrimSpace(host)
if host == "" || strings.ContainsAny(host, " \t\r\n/@\\") {
return "", false
}
hostname, port := host, ""
if parsed, parsedPort, err := net.SplitHostPort(host); err == nil {
hostname, port = parsed, parsedPort
}
if port != "" {
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 || strconv.Itoa(n) != port {
return "", false
}
}
switch strings.ToLower(hostname) {
case "localhost", "127.0.0.1":
if port == "" {
return "http://" + hostname, true
}
return "http://" + hostname + ":" + port, true
case "::1":
if port == "" {
return "http://[::1]", true
}
return "http://[::1]:" + port, true
default:
return "", false
}
}
func pageOriginMatchingHost(page, requestHost string) (string, bool) {
u, err := url.Parse(page)
if err != nil || u.User != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return "", false
}
reqName := requestHostname(requestHost)
if reqName == "" || !strings.EqualFold(u.Hostname(), reqName) {
return "", false
}
return u.Scheme + "://" + u.Host, true
}
func isHTTPOrigin(page string) bool {
u, err := url.Parse(page)
return err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https")
}
func requestHTTPOrigin(r *http.Request) string {
if r == nil {
return ""
}
host := strings.TrimSpace(r.Host)
if host == "" || strings.ContainsAny(host, " \t\r\n/@\\") {
return ""
}
if _, err := url.ParseRequestURI("http://" + host + "/"); err != nil {
return ""
}
scheme := "http"
if r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") {
scheme = "https"
}
return scheme + "://" + host
}
func browserSkillScope(ctx context.Context) browserskill.Scope {
tenant, _ := types.TenantIDFromContext(ctx)
user, _ := types.UserIDFromContext(ctx)
return browserskill.Scope{Tenant: tenant, User: user}
}
// BrowserSkillConnection exposes task status and user controls for an owned conversation.
func (h *Handler) BrowserSkillConnection(c *gin.Context) {
id := c.Param("session_id")
if id == "" {
id = c.Param("id")
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 40*time.Second)
defer cancel()
if _, err := h.sessionService.GetOwnedSession(ctx, id); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
}
c.Header("Cache-Control", "no-store")
scope := browserSkillScope(ctx)
if c.Request.Method == http.MethodGet {
status, err := h.browserSkill.GetStatus(ctx, scope, id)
if err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": status})
return
}
if !h.browserSkill.Enabled() {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "local browser is unavailable"})
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
var input struct {
Action string `json:"action"`
}
if c.ShouldBindJSON(&input) != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid browser action"})
return
}
var err error
switch input.Action {
case "preview":
var frame []byte
frame, err = h.browserSkill.Preview(ctx, scope, id)
if err == nil {
c.Data(http.StatusOK, "application/json", append(append([]byte(`{"success":true,"data":`), frame...), '}'))
return
}
case "focus":
err = h.browserSkill.Focus(ctx, scope, id)
case "select", "start", "resume", "pause", "stop":
err = h.browserSkill.Control(ctx, scope, id, input.Action)
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid browser action"})
return
}
if err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
status, err := h.browserSkill.GetStatus(ctx, scope, id)
if err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": status})
}
// BrowserSkillExtension upgrades a device-authenticated extension connection.
func (h *Handler) BrowserSkillExtension(c *gin.Context) {
h.browserSkill.ServeHTTP(c.Writer, c.Request)
}
// BrowserSkillAccount manages this member's shared browser connection independently
// of any conversation. Normal authentication and tenant membership apply upstream.
func (h *Handler) BrowserSkillAccount(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
defer cancel()
scope := browserSkillScope(ctx)
if scope.User == "" || scope.Tenant == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "login required"})
return
}
c.Header("Cache-Control", "no-store")
if c.Request.Method == http.MethodGet {
status, err := h.browserSkill.Account(ctx, scope)
if err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "browser connection status unavailable"})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": status})
return
}
if !h.browserSkill.Enabled() {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "local browser is unavailable"})
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
var input struct {
Action string `json:"action"`
Origin string `json:"origin"`
}
if c.ShouldBindJSON(&input) != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid browser action"})
return
}
switch input.Action {
case "pair":
link, err := h.browserSkill.Pair(ctx, scope, pairingOrigin(c.Request, input.Origin))
if err != nil {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"pairing_link": link}})
case "revoke":
if err := h.browserSkill.Revoke(ctx, scope); err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "could not revoke browser authorization"})
return
}
status, err := h.browserSkill.Account(ctx, scope)
if err != nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "browser connection status unavailable"})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": status})
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid account browser action"})
}
}
// BrowserSkillAuthorize exchanges one-use pairing and renewable device credentials.
func (h *Handler) BrowserSkillAuthorize(c *gin.Context) {
h.browserSkill.AuthorizeHTTP(c.Writer, c.Request)
}
// BrowserSkillInternal forwards signed requests to the owning node's browser gateway.
func (h *Handler) BrowserSkillInternal(c *gin.Context) {
h.browserSkill.InternalHTTP(c.Writer, c.Request)
}
// BrowserSkillDownload serves the extension archive for installation.
func (h *Handler) BrowserSkillDownload(c *gin.Context) {
h.browserSkill.DownloadExtension(c.Writer, c.Request)
}
@@ -0,0 +1,68 @@
package session
import (
"context"
"encoding/json"
"net/http/httptest"
"testing"
"academy/internal/browserskill"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestBrowserAccountStatusDoesNotRequireConversation(t *testing.T) {
t.Setenv("BROWSERSKILL_BINARY", "/configured/bsk")
t.Setenv("BROWSERSKILL_PUBLIC_URL", "")
h := &Handler{browserSkill: browserskill.NewManager()}
// No session service or conversation ID is supplied: pairing is a personal setting.
request := httptest.NewRequest("GET", "/api/v1/me/browser", nil)
ctx := context.WithValue(request.Context(), types.TenantIDContextKey, uint64(7))
ctx = context.WithValue(ctx, types.UserIDContextKey, "alice")
response := httptest.NewRecorder()
c, _ := gin.CreateTestContext(response)
c.Request = request.WithContext(ctx)
h.BrowserSkillAccount(c)
require.Equal(t, 200, response.Code)
var payload struct {
Data browserskill.Status `json:"data"`
}
require.NoError(t, json.Unmarshal(response.Body.Bytes(), &payload))
require.True(t, payload.Data.Enabled)
require.False(t, payload.Data.Connected)
}
func TestPairingOriginUsesLoopbackListenerForWailsPage(t *testing.T) {
req := httptest.NewRequest("POST", "http://127.0.0.1:53124/api/v1/me/browser", nil)
req.Host = "127.0.0.1:53124"
require.Equal(t, "http://127.0.0.1:53124", pairingOrigin(req, "wails://wails.localhost"))
req.Host = "[::1]:8080"
require.Equal(t, "http://[::1]:8080", pairingOrigin(req, "wails://wails.localhost"))
req.Host = "academy.example"
require.Equal(t, "wails://wails.localhost", pairingOrigin(req, "wails://wails.localhost"))
require.Equal(t, "https://academy.example", pairingOrigin(req, "https://academy.example"))
require.Equal(t, "https://academy.example:8443", pairingOrigin(req, "https://academy.example:8443"))
}
func TestPairingOriginIgnoresForeignHostOnLoopback(t *testing.T) {
req := httptest.NewRequest("POST", "http://127.0.0.1:53124/api/v1/me/browser", nil)
req.Host = "127.0.0.1:53124"
require.Equal(t, "http://127.0.0.1:53124", pairingOrigin(req, "https://evil.example"))
require.Equal(t, "http://127.0.0.1:53124", pairingOrigin(req, "http://127.0.0.1:9"))
req.Host = "academy.example"
require.NotEqual(t, "https://evil.example", pairingOrigin(req, "https://evil.example"))
require.Equal(t, "http://academy.example", pairingOrigin(req, "https://evil.example"))
}
func TestBrowserAccountRequiresUser(t *testing.T) {
h := &Handler{browserSkill: browserskill.NewManager()}
response := httptest.NewRecorder()
c, _ := gin.CreateTestContext(response)
c.Request = httptest.NewRequest("GET", "/api/v1/me/browser", nil)
h.BrowserSkillAccount(c)
require.Equal(t, 401, response.Code)
}
@@ -0,0 +1,51 @@
package session
import (
"context"
"errors"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type chatHistoryTenantStub struct {
interfaces.TenantService
tenants map[uint64]*types.Tenant
}
func (s *chatHistoryTenantStub) GetTenantByID(_ context.Context, id uint64) (*types.Tenant, error) {
if tenant, ok := s.tenants[id]; ok {
return tenant, nil
}
return nil, errors.New("tenant not found")
}
// A shared agent's run carries the agent workspace's tenant info; the chat
// history must still be indexed with the session owner's configuration.
func TestSessionTenantInfoContextUsesTheSessionOwner(t *testing.T) {
owner := &types.Tenant{ID: 84}
session := &types.Tenant{ID: 7}
h := &Handler{tenantService: &chatHistoryTenantStub{tenants: map[uint64]*types.Tenant{7: session}}}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
ctx = context.WithValue(ctx, types.TenantInfoContextKey, owner)
got, ok := h.sessionTenantInfoContext(ctx)
require.True(t, ok)
info, _ := types.TenantInfoFromContext(got)
require.Same(t, session, info)
// Already the session owner's: unchanged.
own := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
own = context.WithValue(own, types.TenantInfoContextKey, session)
got, ok = h.sessionTenantInfoContext(own)
require.True(t, ok)
require.Equal(t, own, got)
// Unknown session tenant: skip indexing rather than use the owner's KB.
missing := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(9))
missing = context.WithValue(missing, types.TenantInfoContextKey, owner)
_, ok = h.sessionTenantInfoContext(missing)
require.False(t, ok)
}
@@ -0,0 +1,41 @@
package session
import (
"context"
"testing"
"time"
"academy/internal/event"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestCommandOutputReachesChatStreamWithoutCompletingTool(t *testing.T) {
ctx := context.Background()
bus := event.NewEventBus()
streams := &completionEventRecorder{}
message := &types.Message{ID: "message"}
h := NewAgentStreamHandler(
ctx, "session", "message", "request", 1, time.Now(), message, streams, bus, nil, nil, nil,
)
h.Subscribe()
for _, done := range []bool{false, true} {
require.NoError(t, bus.Emit(ctx, event.Event{
Type: event.EventAgentCommandOutput,
Data: event.CommandOutputData{
ToolCallID: "call-1", Command: "python analysis.py", Output: "reading CSV", Done: done,
},
}))
}
require.Len(t, streams.events, 2)
for _, e := range streams.events {
require.Equal(t, types.ResponseTypeCommandOutput, e.Type)
require.False(t, e.Done, "command progress is not a completed assistant turn")
frame := buildStreamResponse(e, "request")
require.Equal(t, "call-1", frame.Data["tool_call_id"])
require.Equal(t, "reading CSV", frame.Data["output"])
}
require.Equal(t, true, streams.events[1].Data["done"])
require.Empty(t, message.Content)
require.Empty(t, message.AgentSteps)
}
@@ -0,0 +1,53 @@
package session
import (
"context"
"encoding/json"
"testing"
"time"
"academy/internal/event"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
func publishedCompletion(t *testing.T, data event.AgentCompleteData) interfaces.StreamEvent {
t.Helper()
stream := &completionEventRecorder{}
message := &types.Message{ID: "m"}
handler := NewAgentStreamHandler(
context.Background(), "s", "m", "req", 1, time.Now(), message, stream, nil, nil, nil, nil,
)
require.NoError(t, handler.handleComplete(context.Background(), event.Event{Data: data}))
require.NoError(t, handler.publishCompletion(context.Background()))
last := stream.events[len(stream.events)-1]
require.Equal(t, types.ResponseTypeComplete, last.Type)
return last
}
// A relay that prices a turn's usage needs to know which model produced it.
// The model rides next to usage in the complete event's data, survives the
// stream manager's JSON round trip and reaches the response.
func TestCompletionEventCarriesTheTurnsChatModel(t *testing.T) {
last := publishedCompletion(t, event.AgentCompleteData{
MessageID: "m", ModelID: "model-1",
Usage: &types.TokenUsage{PromptTokens: 10, CompletionTokens: 2, TotalTokens: 12},
})
require.Equal(t, "model-1", last.Data["model_id"])
raw, err := json.Marshal(last)
require.NoError(t, err)
var restored interfaces.StreamEvent
require.NoError(t, json.Unmarshal(raw, &restored))
response := buildStreamResponse(restored, "req")
require.Equal(t, "model-1", response.Data["model_id"])
require.NotNil(t, response.Usage)
}
func TestCompletionEventOmitsAnUnknownModel(t *testing.T) {
last := publishedCompletion(t, event.AgentCompleteData{MessageID: "m"})
require.NotContains(t, last.Data, "model_id")
}
@@ -0,0 +1,76 @@
package session
import (
"strings"
"academy/internal/types/interfaces"
)
// coalesceReplayEvents merges each run of consecutive, unfinished delta
// chunks of one segment (same type and event ID; the types are
// deltaResponseTypes, the ones clients accumulate by event_id) into one event
// that carries the run's concatenated content, its last timestamp and the
// union of its data (later keys win). A done chunk, a chunk of another type
// or of another segment ends the run and passes through untouched, so
// completion markers, durations and references keep their own frames and
// the client's per-event_id accumulation ends with the same text.
//
// Events are stored at the granularity the model emits them, so one long
// answer can mean tens of thousands of frames on replay, each an SSE write, a
// flush and a client-side pass (#3362); this brings it down to a few frames
// per segment. The stored events and their data maps are not modified.
func coalesceReplayEvents(events []interfaces.StreamEvent) []interfaces.StreamEvent {
if len(events) < 2 {
return events
}
out := make([]interfaces.StreamEvent, 0, 16)
var run strings.Builder // content of the open run, written to out's last event when it ends
open := false // whether out's last event is an unfinished run
ownsData := false // whether that event's Data is already a private copy
closeRun := func() {
if open {
out[len(out)-1].Content = run.String()
run.Reset()
open = false
}
}
for _, evt := range events {
mergeable := deltaResponseTypes[evt.Type] && !evt.Done
if open {
last := &out[len(out)-1]
if mergeable && last.Type == evt.Type && last.ID == evt.ID {
run.WriteString(evt.Content)
last.Timestamp = evt.Timestamp
if len(evt.Data) > 0 {
if !ownsData {
last.Data = copyEventData(last.Data, len(evt.Data))
ownsData = true
}
for key, value := range evt.Data {
last.Data[key] = value
}
}
continue
}
closeRun()
}
out = append(out, evt)
if mergeable {
run.WriteString(evt.Content)
open = true
ownsData = false
}
}
closeRun()
return out
}
// copyEventData returns a private copy of a stored event's data map with room
// for extra keys; the original may be shared with the store's own buffer.
func copyEventData(data map[string]interface{}, extra int) map[string]interface{} {
copied := make(map[string]interface{}, len(data)+extra)
for key, value := range data {
copied[key] = value
}
return copied
}
@@ -0,0 +1,214 @@
package session
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
func chunk(id string, kind types.ResponseType, content string) interfaces.StreamEvent {
return interfaces.StreamEvent{ID: id, Type: kind, Content: content, Data: map[string]interface{}{"event_id": id}}
}
func doneChunk(id string, kind types.ResponseType, content string) interfaces.StreamEvent {
evt := chunk(id, kind, content)
evt.Done = true
evt.Data["duration_ms"] = int64(1200)
return evt
}
func TestCoalesceReplayEvents_MergesTheChunksOfOneSegmentIntoOneFrame(t *testing.T) {
t1, t2, t3 := time.Unix(1, 0), time.Unix(2, 0), time.Unix(3, 0)
a := chunk("think-1", types.ResponseTypeThinking, "Let ")
b := chunk("think-1", types.ResponseTypeThinking, "me ")
c := chunk("think-1", types.ResponseTypeThinking, "see.")
a.Timestamp, b.Timestamp, c.Timestamp = t1, t2, t3
b.Data["is_fallback"] = true
got := coalesceReplayEvents([]interfaces.StreamEvent{a, b, c})
require.Len(t, got, 1)
assert.Equal(t, "Let me see.", got[0].Content)
assert.Equal(t, "think-1", got[0].ID)
assert.False(t, got[0].Done)
assert.Equal(t, t3, got[0].Timestamp)
assert.Equal(t, map[string]interface{}{"event_id": "think-1", "is_fallback": true}, got[0].Data)
// The stored events keep their own content and data.
assert.Equal(t, "Let ", a.Content)
assert.Equal(t, map[string]interface{}{"event_id": "think-1"}, a.Data)
assert.Equal(t, map[string]interface{}{"event_id": "think-1"}, c.Data)
}
func TestCoalesceReplayEvents_ADoneChunkKeepsItsOwnFrame(t *testing.T) {
// The client marks a segment finished on its done chunk without appending
// that chunk's content, so a done chunk must never absorb earlier text.
got := coalesceReplayEvents([]interfaces.StreamEvent{
chunk("ans-1", types.ResponseTypeAnswer, "The answer "),
chunk("ans-1", types.ResponseTypeAnswer, "is 42."),
doneChunk("ans-1", types.ResponseTypeAnswer, ""),
chunk("ans-2", types.ResponseTypeAnswer, "Next."),
})
require.Len(t, got, 3)
assert.Equal(t, "The answer is 42.", got[0].Content)
assert.False(t, got[0].Done)
assert.True(t, got[1].Done)
assert.Equal(t, int64(1200), got[1].Data["duration_ms"])
assert.Equal(t, "Next.", got[2].Content)
}
func TestCoalesceReplayEvents_AnotherSegmentOrTypeEndsTheRun(t *testing.T) {
got := coalesceReplayEvents([]interfaces.StreamEvent{
chunk("think-1", types.ResponseTypeThinking, "a"),
chunk("think-2", types.ResponseTypeThinking, "b"),
chunk("think-1", types.ResponseTypeThinking, "c"),
chunk("ans-1", types.ResponseTypeAnswer, "d"),
{
ID: "tool-1", Type: types.ResponseTypeToolCall, Content: "Calling tool: search",
Data: map[string]interface{}{"tool": "search"},
},
chunk("ans-1", types.ResponseTypeAnswer, "e"),
// Same event ID, different type: two segments as far as the client
// is concerned, so two frames.
chunk("ans-1", types.ResponseTypeThinking, "f"),
{ID: "complete-1", Type: types.ResponseTypeComplete, Done: true},
})
require.Len(t, got, 8)
for i, want := range []string{"a", "b", "c", "d", "Calling tool: search", "e", "f", ""} {
assert.Equal(t, want, got[i].Content, "frame %d", i)
}
assert.Equal(t, types.ResponseTypeToolCall, got[4].Type)
assert.Equal(t, types.ResponseTypeThinking, got[6].Type)
assert.Equal(t, types.ResponseTypeComplete, got[7].Type)
}
func TestCoalesceReplayEvents_MergesReflectionChunksToo(t *testing.T) {
got := coalesceReplayEvents([]interfaces.StreamEvent{
chunk("refl-1", types.ResponseTypeReflection, "Looks "),
chunk("refl-1", types.ResponseTypeReflection, "right."),
})
require.Len(t, got, 1)
assert.Equal(t, "Looks right.", got[0].Content)
}
func TestCoalesceReplayEvents_LeavesShortInputsAlone(t *testing.T) {
assert.Empty(t, coalesceReplayEvents(nil))
one := []interfaces.StreamEvent{chunk("ans-1", types.ResponseTypeAnswer, "x")}
assert.Equal(t, one, coalesceReplayEvents(one))
}
// A long turn stored chunk by chunk replays as a handful of frames, and the
// client still receives every character in order.
func TestContinueStream_ReplaysALongAnswerInAFewFrames(t *testing.T) {
var events []interfaces.StreamEvent
var thought, answer strings.Builder
for i := 0; i < 2000; i++ {
piece := fmt.Sprintf("t%d ", i)
thought.WriteString(piece)
events = append(events, chunk("think-1", types.ResponseTypeThinking, piece))
}
events = append(events, doneChunk("think-1", types.ResponseTypeThinking, ""))
for i := 0; i < 3000; i++ {
piece := fmt.Sprintf("a%d ", i)
answer.WriteString(piece)
events = append(events, chunk("ans-1", types.ResponseTypeAnswer, piece))
}
events = append(events,
doneChunk("ans-1", types.ResponseTypeAnswer, ""),
interfaces.StreamEvent{ID: "complete-1", Type: types.ResponseTypeComplete, Done: true})
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{
sessionService: &stubSessionService{},
messageService: &stubMessageServiceForStream{},
streamManager: &stubStreamManager{events: events},
fileService: &stubResourceFileService{},
}
r.GET("/sessions/continue-stream/:session_id", h.ContinueStream)
recorder := httptest.NewRecorder()
r.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/sessions/continue-stream/sess1?message_id=msg1", nil))
require.Equal(t, http.StatusOK, recorder.Code)
body := recorder.Body.String()
// thinking run, thinking done, answer run, answer done, complete.
assert.Equal(t, 5, strings.Count(body, "event:message"), body)
assert.Contains(t, body, thought.String())
assert.Contains(t, body, answer.String())
assert.Less(t, strings.Index(body, thought.String()), strings.Index(body, answer.String()))
}
// growingStreamManager shows `visible` events on the first read and the whole
// log afterwards, so the handler replays a prefix and polls for the rest.
type growingStreamManager struct {
stubStreamManager
mu sync.Mutex
visible int
reads int
}
func (g *growingStreamManager) GetEvents(
_ context.Context, _, _ string, from int,
) ([]interfaces.StreamEvent, int, error) {
g.mu.Lock()
defer g.mu.Unlock()
g.reads++
limit := g.visible
if g.reads > 1 {
limit = len(g.events)
}
if from >= limit {
return nil, from, nil
}
return g.events[from:limit], limit, nil
}
// A storage reference cut between the replayed prefix and the chunks that
// arrive through the poll loop is still reassembled: the merged replay frame
// goes through the same holdback buffer as the live chunks after it.
func TestContinueStream_ReplayHoldbackSurvivesToThePollLoop(t *testing.T) {
events := []interfaces.StreamEvent{
chunk("answer-1", types.ResponseTypeAnswer, "The diagram "),
chunk("answer-1", types.ResponseTypeAnswer, "![fig](resource://xifDo7"),
// replay ends here (visible: 2); the rest arrives through the poll loop
chunk("answer-1", types.ResponseTypeAnswer, "NTSL300Lp1goVutw) shows the flow."),
doneChunk("answer-1", types.ResponseTypeAnswer, ""),
{ID: "complete-1", Type: types.ResponseTypeComplete, Done: true},
}
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{
sessionService: &stubSessionService{},
messageService: &stubMessageServiceForStream{},
streamManager: &growingStreamManager{stubStreamManager: stubStreamManager{events: events}, visible: 2},
fileService: &stubResourceFileService{},
}
r.GET("/sessions/continue-stream/:session_id", h.ContinueStream)
recorder := httptest.NewRecorder()
r.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet,
"/sessions/continue-stream/sess1?message_id=msg1&resource_urls=public", nil))
require.Equal(t, http.StatusOK, recorder.Code)
body := recorder.Body.String()
assert.NotContains(t, body, "resource://")
assert.Contains(t, body, `![fig](https://cdn.example.com/signed.png) shows the flow.`)
assert.Less(t, strings.LastIndex(body, `"response_type":"answer"`),
strings.Index(body, `"response_type":"complete"`))
}
@@ -0,0 +1,188 @@
package session
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// The stubs below implement only the methods ContinueStream reaches; embedding
// each interface keeps everything else nil-panicky so an un-stubbed call fails
// loudly rather than returning a zero value.
type stubSessionService struct {
interfaces.SessionService
// session, when set, is the row GetSession returns. Background-work tests
// use it so the handler must key work by session.TenantID.
session *types.Session
}
func (s *stubSessionService) GetSession(_ context.Context, id string) (*types.Session, error) {
if s != nil && s.session != nil {
return s.session, nil
}
return &types.Session{ID: id, TenantID: 1}, nil
}
type stubMessageServiceForStream struct {
interfaces.MessageService
}
func (s *stubMessageServiceForStream) GetMessage(
_ context.Context, sessionID, messageID string,
) (*types.Message, error) {
return &types.Message{ID: messageID, SessionID: sessionID, RequestID: "req-1"}, nil
}
// stubStreamManager replays a fixed event list, mimicking a completed stream.
type stubStreamManager struct {
events []interfaces.StreamEvent
}
func (s *stubStreamManager) AppendEvent(
context.Context, string, string, interfaces.StreamEvent,
) error {
return nil
}
func (s *stubStreamManager) GetEvents(
_ context.Context, _, _ string, fromOffset int,
) ([]interfaces.StreamEvent, int, error) {
if fromOffset >= len(s.events) {
return nil, len(s.events), nil
}
return s.events[fromOffset:], len(s.events), nil
}
func (s *stubStreamManager) AppendSteerEvents(
context.Context, string, string, []interfaces.StreamEvent,
) error {
return nil
}
func (s *stubStreamManager) GetSteerEvents(
_ context.Context, _, _ string, fromOffset int,
) ([]interfaces.StreamEvent, int, error) {
return nil, fromOffset, nil
}
func (s *stubStreamManager) UpdateSteerEventData(
context.Context, string, string, string, map[string]interface{},
) (bool, error) {
return false, nil
}
func (s *stubStreamManager) DeleteSteerEvent(
context.Context, string, string, string,
) (bool, error) {
return false, nil
}
func (s *stubStreamManager) SetLiveRun(context.Context, string, string, string) error {
return nil
}
func (s *stubStreamManager) ClaimLiveRun(context.Context, string, string, string) error {
return nil
}
func (s *stubStreamManager) GetLiveRun(context.Context, string) (string, string, error) {
return "", "", nil
}
func (s *stubStreamManager) ClearLiveRun(context.Context, string, string) error {
return nil
}
func (s *stubStreamManager) ResetEvents(context.Context, string, string) error { return nil }
// completedAnswerStream is one assistant turn whose answer embeds a knowledge-base
// image, with the resource handle straddling two deltas as it does in production
// when the model-context decoder flushes mid-reference.
func completedAnswerStream() []interfaces.StreamEvent {
return []interfaces.StreamEvent{
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "The diagram ![fig](resource://xifDo7"},
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "NTSL300Lp1goVutw) shows the flow."},
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "", Done: true},
{ID: "refs-1", Type: types.ResponseTypeReferences, Data: map[string]interface{}{
"references": types.References{{
ID: "chunk-1",
Content: "figure ![f](" + testResourceHandle + ")",
ImageInfo: `[{"url":"` + testResourceHandle + `"}]`,
}},
}},
{ID: "complete-1", Type: types.ResponseTypeComplete, Done: true},
}
}
func newContinueStreamRouter(t *testing.T) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{
sessionService: &stubSessionService{},
messageService: &stubMessageServiceForStream{},
streamManager: &stubStreamManager{events: completedAnswerStream()},
fileService: &stubResourceFileService{},
}
r.GET("/sessions/continue-stream/:session_id", h.ContinueStream)
return r
}
func continueStream(t *testing.T, query string) (int, string) {
t.Helper()
recorder := httptest.NewRecorder()
newContinueStreamRouter(t).ServeHTTP(recorder, httptest.NewRequest(
http.MethodGet, "/sessions/continue-stream/sess1?message_id=msg1"+query, nil))
return recorder.Code, recorder.Body.String()
}
// Default behaviour: the SSE stream keeps carrying internal handles, which the
// Academy frontend resolves through the authenticated /files proxy.
func TestContinueStream_DefaultEmitsHandles(t *testing.T) {
code, body := continueStream(t, "")
require.Equal(t, http.StatusOK, code, body)
assert.Contains(t, body, testResourceHandle)
assert.NotContains(t, body, "cdn.example.com")
}
// With resource_urls=public the whole stream — answer text and the references
// payload — carries URLs a third-party app can load directly.
func TestContinueStream_PublicModeEmitsLoadableURLs(t *testing.T) {
code, body := continueStream(t, "&resource_urls=public")
require.Equal(t, http.StatusOK, code, body)
assert.NotContains(t, body, "resource://",
"no internal handle may reach a client that asked for public URLs")
assert.Contains(t, body, "https://cdn.example.com/signed.png")
// The handle was split across two answer deltas; the reassembled Markdown
// image must be intact rather than broken in half.
assert.Contains(t, body, `![fig](https://cdn.example.com/signed.png) shows the flow.`)
// The references payload carries both the chunk text and image_info.
assert.Contains(t, body, `figure ![f](https://cdn.example.com/signed.png)`)
assert.Contains(t, body, `[{\"url\":\"https://cdn.example.com/signed.png\"}]`)
// Every answer delta must precede the completion marker.
assert.Less(t, strings.LastIndex(body, `"response_type":"answer"`),
strings.Index(body, `"response_type":"complete"`))
}
func TestContinueStream_RejectsInvalidResourceURLMode(t *testing.T) {
code, body := continueStream(t, "&resource_urls=signed")
assert.Equal(t, http.StatusBadRequest, code, body)
assert.Contains(t, body, "resource_urls")
}
@@ -0,0 +1,85 @@
package session
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type resumeStreamMessageService struct {
interfaces.MessageService
completed bool
}
func (s *resumeStreamMessageService) GetMessage(
_ context.Context, sessionID, messageID string,
) (*types.Message, error) {
return &types.Message{ID: messageID, SessionID: sessionID, IsCompleted: s.completed}, nil
}
func TestContinueStreamWaitsForApprovedSegment(t *testing.T) {
for _, tt := range []struct {
name string
query string
marker interfaces.StreamEvent
completed bool
status int
}{
{name: "ordinary replay", status: http.StatusOK},
{name: "old terminal segment", query: "&resume_pending_id=p", status: http.StatusConflict},
{
name: "different approval", query: "&resume_pending_id=p", status: http.StatusConflict,
marker: interfaces.StreamEvent{
Type: types.ResponseTypeAgentQuery, Data: map[string]interface{}{"resume_pending_id": "old"},
},
},
{
name: "automation resumed", query: "&resume_pending_id=p", status: http.StatusOK,
marker: interfaces.StreamEvent{
Type: types.ResponseTypeAgentQuery, Data: map[string]interface{}{"resume_pending_id": "p"},
},
},
{
name: "chat resumed", query: "&resume_pending_id=p", status: http.StatusOK,
marker: interfaces.StreamEvent{
Type: types.ResponseTypeRunResumed, Data: map[string]interface{}{"pending_id": "p"},
},
},
{
name: "terminal failure before resume marker", query: "&resume_pending_id=p",
completed: true, status: http.StatusOK,
},
} {
t.Run(tt.name, func(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
events := []interfaces.StreamEvent{}
if tt.marker.Type != "" {
events = append(events, tt.marker)
}
events = append(events, interfaces.StreamEvent{Type: types.ResponseTypeComplete, Done: true})
h := &Handler{
sessionService: &stubSessionService{},
messageService: &resumeStreamMessageService{completed: tt.completed},
streamManager: &stubStreamManager{events: events},
}
r.GET("/sessions/continue-stream/:session_id", h.ContinueStream)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/sessions/continue-stream/s?message_id=m"+tt.query, nil)
r.ServeHTTP(recorder, request)
require.Equal(t, tt.status, recorder.Code, recorder.Body.String())
if tt.status == http.StatusConflict {
require.NotContains(t, recorder.Body.String(), `"response_type":"complete"`)
require.NotContains(t, recorder.Header().Get("Content-Type"), "text/event-stream")
} else {
require.Contains(t, recorder.Body.String(), `"response_type":"complete"`)
}
})
}
}
@@ -0,0 +1,108 @@
package session
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
type capturingSessionService struct {
interfaces.SessionService
owner *hostCreateHandler
}
func (s *capturingSessionService) CreateSession(_ context.Context, session *types.Session) (*types.Session, error) {
copied := *session
if copied.ID == "" {
copied.ID = "sess-test"
}
s.owner.created = &copied
return s.owner.created, nil
}
type hostCreateHandler struct {
*Handler
created *types.Session
}
func handlerWithApprovedDirs(dirs ...string) *hostCreateHandler {
copied := append([]string(nil), dirs...)
h := &hostCreateHandler{}
svc := &capturingSessionService{owner: h}
h.Handler = &Handler{
sessionService: svc,
approvedProjectDirs: func() []string {
return copied
},
}
return h
}
func postSession(t *testing.T, h *hostCreateHandler, body string) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Next()
})
r.POST("/sessions", h.CreateSession)
req := httptest.NewRequest(http.MethodPost, "/sessions", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w
}
// The workspace directory must come from the user-approved list. Accepting an
// arbitrary path would let anything that can reach this endpoint point the
// sandbox at the filesystem root.
func TestCreateSessionRejectsUnapprovedProjectDir(t *testing.T) {
h := handlerWithApprovedDirs("/Users/dev/My Project")
w := postSession(t, h, `{"project_dir":"/"}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestCreateSessionRejectsProjectDirWhenNoneApproved(t *testing.T) {
h := handlerWithApprovedDirs()
w := postSession(t, h, `{"project_dir":"/Users/dev/My Project"}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestCreateSessionStoresApprovedProjectDir(t *testing.T) {
h := handlerWithApprovedDirs("/Users/dev/My Project")
w := postSession(t, h, `{"project_dir":"/Users/dev/My Project"}`)
require.Equal(t, http.StatusCreated, w.Code)
require.Equal(t, "/Users/dev/My Project", h.created.HostWorkspaceDir)
}
func TestCreateSessionStoresCleanedApprovedProjectDir(t *testing.T) {
h := handlerWithApprovedDirs("/Users/dev/My Project")
w := postSession(t, h, `{"project_dir":"/Users/dev/My Project/"}`)
require.Equal(t, http.StatusCreated, w.Code)
require.Equal(t, "/Users/dev/My Project", h.created.HostWorkspaceDir)
}
func TestCreateSessionRejectsRelativeProjectDir(t *testing.T) {
h := handlerWithApprovedDirs("/Users/dev/My Project")
w := postSession(t, h, `{"project_dir":"My Project"}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
// Omitting it is the normal path: the session gets an auto workspace.
func TestCreateSessionWithoutProjectDirLeavesItEmpty(t *testing.T) {
h := handlerWithApprovedDirs("/Users/dev/My Project")
w := postSession(t, h, `{"title":"hello"}`)
require.Equal(t, http.StatusCreated, w.Code)
require.NotNil(t, h.created)
require.Empty(t, h.created.HostWorkspaceDir)
}
+115
View File
@@ -0,0 +1,115 @@
package session
import (
"context"
stderrors "errors"
"net/http"
"strings"
"academy/internal/application/service"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
// sessionForker is the fork surface the handler needs. Declaring it here
// rather than depending on *service.SessionForkService keeps the handler
// testable with a stub.
type sessionForker interface {
Fork(
ctx context.Context,
tenantID uint64,
userID, sourceSessionID, messageID, title string,
) (*service.ForkResult, error)
}
// ForkSessionRequest is the fork endpoint's body.
type ForkSessionRequest struct {
// MessageID is the message to branch at. A user message copies history
// strictly before it (the client prefills that question). An assistant
// message copies history through that answer so the branch continues after it.
MessageID string `json:"message_id" binding:"required"`
// Title is optional. Empty falls back to the source title plus a suffix.
Title string `json:"title"`
}
// ForkSession godoc
// @Summary 分叉会话
// @Description 从指定的用户或助手消息处分叉出一个新会话。用户消息:复制其之前的历史并预填该问题;助手消息:复制含该回答在内的历史,从该轮沙箱状态继续。
// @Tags 会话
// @Accept json
// @Produce json
// @Param session_id path string true "源会话 ID"
// @Param request body ForkSessionRequest true "分叉请求"
// @Success 200 {object} map[string]interface{} "新会话"
// @Failure 400 {object} errors.AppError "请求参数错误 / 分叉点角色不支持"
// @Failure 404 {object} errors.AppError "会话或消息不存在"
// @Failure 409 {object} errors.AppError "源会话正在生成中"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/fork [post]
func (h *Handler) ForkSession(c *gin.Context) {
ctx := c.Request.Context()
sessionID := strings.TrimSpace(c.Param("session_id"))
if sessionID == "" {
sessionID = strings.TrimSpace(c.Param("id"))
}
if sessionID == "" {
_ = c.Error(errors.NewBadRequestError("session ID is required"))
return
}
var req ForkSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("message_id is required"))
return
}
if strings.TrimSpace(req.MessageID) == "" {
_ = c.Error(errors.NewBadRequestError("message_id is required"))
return
}
if h.forkService == nil {
_ = c.Error(errors.NewBadRequestError("session fork is not available"))
return
}
tenantID, _ := types.TenantIDFromContext(ctx)
userID := types.SessionOwnerIDFromContext(ctx)
result, err := h.forkService.Fork(
ctx, tenantID, userID, sessionID,
strings.TrimSpace(req.MessageID), strings.TrimSpace(req.Title),
)
if err != nil {
// A busy source is a retryable, user-actionable state, not a fault:
// snapshotting would pause the sandbox and interrupt the running turn.
if stderrors.Is(err, service.ErrForkSourceBusy) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": "source session has an active turn",
"code": "FORK_SOURCE_BUSY",
})
return
}
if stderrors.Is(err, service.ErrForkSessionNotFound) {
_ = c.Error(errors.NewNotFoundError("session not found"))
return
}
if stderrors.Is(err, service.ErrForkMessageNotFound) {
_ = c.Error(errors.NewNotFoundError("message not found"))
return
}
if stderrors.Is(err, service.ErrForkMessageNotUser) {
_ = c.Error(errors.NewBadRequestError("fork point must be a user or assistant message"))
return
}
logger.Errorf(ctx, "fork session %s failed: %v", sessionID, err)
_ = c.Error(errors.NewInternalServerError("fork session failed"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
+135
View File
@@ -0,0 +1,135 @@
package session
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/service"
"academy/internal/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type stubForker struct {
result *service.ForkResult
err error
gotMsg string
gotTit string
}
func (s *stubForker) Fork(
_ context.Context, _ uint64, _, _, messageID, title string,
) (*service.ForkResult, error) {
s.gotMsg = messageID
s.gotTit = title
return s.result, s.err
}
func performFork(t *testing.T, forker sessionForker, body string) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
h := &Handler{forkService: forker}
w := httptest.NewRecorder()
r := gin.New()
r.Use(middleware.ErrorHandler())
r.POST("/sessions/:session_id/fork", h.ForkSession)
req := httptest.NewRequest(http.MethodPost, "/sessions/src/fork", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w
}
func TestForkSessionReturnsNewSessionID(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{SessionID: "new-1"}}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "u-2", forker.gotMsg)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
data := body["data"].(map[string]any)
require.Equal(t, "new-1", data["session_id"])
require.Equal(t, false, data["degraded"])
}
func TestForkSessionSurfacesDegradeReason(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{
SessionID: "new-1", Degraded: true, Reason: service.ForkDegradeSandboxGone,
}}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusOK, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
data := body["data"].(map[string]any)
require.Equal(t, true, data["degraded"])
require.Equal(t, "SANDBOX_GONE", data["reason"])
}
func TestForkSessionMapsBusySourceTo409(t *testing.T) {
forker := &stubForker{err: service.ErrForkSourceBusy}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusConflict, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, "FORK_SOURCE_BUSY", body["code"])
}
func TestForkSessionMapsMissingSessionTo404(t *testing.T) {
forker := &stubForker{err: service.ErrForkSessionNotFound}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestForkSessionMapsMissingMessageTo404(t *testing.T) {
forker := &stubForker{err: service.ErrForkMessageNotFound}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestForkSessionMapsNonUserForkPointTo400(t *testing.T) {
forker := &stubForker{err: service.ErrForkMessageNotUser}
w := performFork(t, forker, `{"message_id":"a-1"}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestForkSessionRejectsMissingMessageID(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{SessionID: "new-1"}}
w := performFork(t, forker, `{}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestForkSessionMapsUnknownErrorTo500(t *testing.T) {
forker := &stubForker{err: errors.New("boom")}
w := performFork(t, forker, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusInternalServerError, w.Code)
}
func TestForkSessionPassesTitleThrough(t *testing.T) {
forker := &stubForker{result: &service.ForkResult{SessionID: "new-1"}}
performFork(t, forker, `{"message_id":"u-2","title":"我的分支"}`)
require.Equal(t, "我的分支", forker.gotTit)
}
+677
View File
@@ -0,0 +1,677 @@
package session
import (
"context"
stderrors "errors"
"net/http"
"academy/internal/agent/hitl"
"academy/internal/application/service"
"academy/internal/browserskill"
"academy/internal/config"
"academy/internal/errors"
"academy/internal/infrastructure/docparser"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
)
// Handler handles all HTTP requests related to conversation sessions
type Handler struct {
browserSkill *browserskill.Manager
messageService interfaces.MessageService // Service for managing messages
suggestionService interfaces.MessageSuggestionService
sessionService interfaces.SessionService // Service for managing sessions
streamManager interfaces.StreamManager // Manager for handling streaming responses
config *config.Config // Application configuration
knowledgebaseService interfaces.KnowledgeBaseService // Service for managing knowledge bases
customAgentService interfaces.CustomAgentService // Service for managing custom agents
tenantService interfaces.TenantService // Service for loading tenant (shared agent context)
agentShareService interfaces.AgentShareService // Service for resolving shared agents (KB scope in retrieval)
kbShareService interfaces.KBShareService // Service for resolving shared KB permissions
fileService interfaces.FileService // Service for file storage (image uploads)
resourceCatalog interfaces.ResourceCatalog
storageResolver interfaces.StorageBackendResolver
modelService interfaces.ModelService // Service for model management (VLM access)
attachmentProcessor *AttachmentProcessor // Processor for file attachments
temporaryDocuments interfaces.TemporaryDocumentService
// artifactCollector drains skill-generated files from the session sandbox
// after an agent turn completes. May be nil when the sandbox backend does
// not support artifact collection; handlers must check before using.
artifactCollector *service.ArtifactCollector
// workspaceCheckpointer commits the sandbox /workspace at the end of each
// agent turn so session fork can roll back to a specific message. May be
// nil when the deployment has no sandbox backend.
workspaceCheckpointer *service.WorkspaceCheckpointer
// sandboxIDLookup resolves a session's bound sandbox without provisioning.
sandboxIDLookup SandboxIDLookup
memoryService interfaces.MemoryService // Service for cross-session long-term memory
// userService / memberService back the sandbox terminal's self-contained
// handshake (browser WebSocket upgrades cannot send Authorization).
userService interfaces.UserService
memberService interfaces.TenantMemberService
// terminalService opens PTYs on the sandbox bound to a session. It also
// owns first-use provisioning: the WS handshake carries the chat page's
// selected agent so the sandbox is created with the same config a
// conversation turn would use.
terminalService *service.SandboxTerminalService
desktopService *service.SandboxDesktopService
desktopTickets service.SandboxDesktopTicketStore
desktopLast service.SandboxDesktopLastStore
// redis backs the distributed desktop slot. Nil in Lite mode, where the
// in-process limiter is the correct degradation.
redis *redis.Client
// forkService branches a session at a chosen user message. May be nil in
// deployments where fork is not wired; ForkSession checks.
forkService sessionForker
// rewindService truncates the current session at a chosen message. May
// be nil in deployments where rewind is not wired; RewindSession checks.
rewindService sessionRewinder
// approvedProjectDirs is the user-approved ProjectDirs list used to
// validate CreateSession's optional project_dir. Nil means none are
// approved, so a non-empty project_dir is rejected.
approvedProjectDirs HostProjectDirsLoader
// promptBroker and suspendedRuns resume and supersede runs suspended on
// agent prompts. Nil leaves suspended prompts to the reaper.
promptBroker *hitl.Broker
suspendedRuns *service.SuspendedRunService
stopCollaboration func(context.Context, string, string) error
delegatedPrompt func(context.Context, *types.AgentPrompt) bool
background *service.BackgroundWork
}
// NewHandler creates a new instance of Handler with all necessary dependencies
func NewHandler(
sessionService interfaces.SessionService,
messageService interfaces.MessageService,
suggestionService interfaces.MessageSuggestionService,
streamManager interfaces.StreamManager,
config *config.Config,
knowledgebaseService interfaces.KnowledgeBaseService,
customAgentService interfaces.CustomAgentService,
tenantService interfaces.TenantService,
agentShareService interfaces.AgentShareService,
kbShareService interfaces.KBShareService,
fileService interfaces.FileService,
resourceCatalog interfaces.ResourceCatalog,
storageResolver interfaces.StorageBackendResolver,
modelService interfaces.ModelService,
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
temporaryDocuments interfaces.TemporaryDocumentService,
artifactCollector *service.ArtifactCollector,
workspaceCheckpointer *service.WorkspaceCheckpointer,
sandboxIDLookup SandboxIDLookup,
memoryService interfaces.MemoryService,
userService interfaces.UserService,
memberService interfaces.TenantMemberService,
terminalService *service.SandboxTerminalService,
browserSkill *browserskill.Manager,
desktopService *service.SandboxDesktopService,
desktopTickets service.SandboxDesktopTicketStore,
desktopLast service.SandboxDesktopLastStore,
rdb *redis.Client,
forkService *service.SessionForkService,
rewindService *service.SessionRewindService,
approvedProjectDirs HostProjectDirsLoader,
backgroundWork *service.BackgroundWork,
) *Handler {
h := &Handler{
browserSkill: browserSkill,
sessionService: sessionService,
messageService: messageService,
suggestionService: suggestionService,
streamManager: streamManager,
config: config,
knowledgebaseService: knowledgebaseService,
customAgentService: customAgentService,
tenantService: tenantService,
agentShareService: agentShareService,
kbShareService: kbShareService,
fileService: fileService,
resourceCatalog: resourceCatalog,
storageResolver: storageResolver,
modelService: modelService,
temporaryDocuments: temporaryDocuments,
artifactCollector: artifactCollector,
workspaceCheckpointer: workspaceCheckpointer,
sandboxIDLookup: sandboxIDLookup,
memoryService: memoryService,
userService: userService,
memberService: memberService,
terminalService: terminalService,
desktopService: desktopService,
desktopTickets: desktopTickets,
desktopLast: desktopLast,
redis: rdb,
approvedProjectDirs: approvedProjectDirs,
background: backgroundWork,
attachmentProcessor: NewAttachmentProcessor(
fileService,
documentReader,
imageResolver,
modelService,
),
}
if forkService != nil {
h.forkService = forkService
}
if rewindService != nil {
h.rewindService = rewindService
}
return h
}
// CreateSession godoc
// @Summary 创建会话
// @Description 创建新的对话会话。
// @Description kind 为空时为普通会话,assistant 为助手会话。
// @Tags 会话
// @Accept json
// @Produce json
// @Param request body CreateSessionRequest true "会话创建请求"
// @Success 201 {object} map[string]interface{} "创建的会话"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions [post]
func (h *Handler) CreateSession(c *gin.Context) {
ctx := c.Request.Context()
// Parse and validate the request body
var request CreateSessionRequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to validate session creation parameters", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if !types.IsValidSessionKind(request.Kind) {
_ = c.Error(errors.NewBadRequestError("invalid session kind"))
return
}
// Get tenant ID from context
tenantID, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
logger.Error(ctx, "Failed to get tenant ID")
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
// Sessions are now knowledge-base-independent:
// - All configuration comes from custom agent at query time
// - Session only stores basic info (tenant ID, title, description)
logger.Infof(
ctx,
"Processing session creation request, tenant ID: %d",
tenantID,
)
hostDir, ok := bindHostWorkspaceDir(request.ProjectDir, h.approvedDirs())
if !ok {
_ = c.Error(errors.NewBadRequestError("project_dir is not an approved project directory"))
return
}
// Create session object with base properties
createdSession := &types.Session{
TenantID: tenantID.(uint64),
Kind: request.Kind,
Title: request.Title,
Description: types.SanitizeClientSessionDescription(request.Description, ""),
HostWorkspaceDir: hostDir,
}
// Attach the calling user as the session owner when available.
// API-key callers scope sessions per external user when configured;
// otherwise they fall back to the synthetic tenant user.
if ownerID := types.SessionOwnerIDFromContext(ctx); ownerID != "" {
createdSession.UserID = ownerID
}
// Call service to create session
logger.Infof(ctx, "Calling session service to create session")
createdSession, err := h.sessionService.CreateSession(ctx, createdSession)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Return created session
logger.Infof(ctx, "Session created successfully, ID: %s", createdSession.ID)
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": createdSession,
})
}
// GetSession godoc
// @Summary 获取会话详情
// @Description 根据ID获取会话详情
// @Tags 会话
// @Accept json
// @Produce json
// @Param id path string true "会话ID"
// @Success 200 {object} map[string]interface{} "会话详情"
// @Failure 404 {object} errors.AppError "会话不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{id} [get]
func (h *Handler) GetSession(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving session")
// Get session ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Call service to get session details
logger.Infof(ctx, "Retrieving session, ID: %s", id)
session, err := h.sessionService.GetSession(ctx, id)
if err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "Session not found, ID: %s", id)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Return session data
logger.Infof(ctx, "Session retrieved successfully, ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": session,
})
}
// GetSessionsByTenant godoc
// @Summary 获取会话列表
// @Description 获取当前空间的会话列表,支持分页、关键字搜索、按来源/Agent 筛选
// @Tags 会话
// @Accept json
// @Produce json
// @Param page query int false "页码" minimum(1) extensions(x-agent,x-agent-maximum=10000)
// @Param page_size query int false "每页数量" minimum(1) maximum(1000) extensions(x-agent,x-agent-maximum=20)
// @Param kind query string false "会话类型:空值仅普通会话;assistant 仅当前用户的助手会话" Enums(assistant) extensions(x-agent)
// @Param keyword query string false "标题模糊搜索" extensions(x-agent)
// @Param source query string false "来源过滤:web / embed / api / feishu / wechat / slack / ...(api、embed、IM 渠道需 Admin+)"
// @Param agent_id query string false "按 Agent 过滤(仅对 IM 会话生效)"
// @Success 200 {object} sessionListResponse "会话列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"session.list","risk":"read"}
// @x-agent-hint "The user's own conversations, pinned ones first, then most recently active. keyword matches titles only, which are often auto-generated; to find a conversation by what was said, use message.search. Read one with message.list."
// @Router /sessions [get]
func (h *Handler) GetSessionsByTenant(c *gin.Context) {
ctx := c.Request.Context()
kind := c.Query("kind")
if !types.IsValidSessionKind(kind) {
_ = c.Error(errors.NewBadRequestError("invalid session kind"))
return
}
// Parse pagination parameters from query
var pagination types.Pagination
if err := c.ShouldBindQuery(&pagination); err != nil {
logger.Error(ctx, "Failed to parse pagination parameters", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
// Response items always include pin state and (when available) IM origin
// fields so the frontend can render pin icons / source badges without a
// second roundtrip. An omitted kind selects normal conversations.
result, err := h.sessionService.ListSessions(ctx, &types.SessionListQuery{
Kind: kind,
Keyword: c.Query("keyword"),
Source: c.Query("source"),
AgentID: c.Query("agent_id"),
Page: pagination.Page,
PageSize: pagination.PageSize,
})
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
items, _ := result.Data.([]*types.SessionListItem)
c.JSON(http.StatusOK, sessionListResponse{
Success: true,
Data: items,
Total: result.Total,
Page: result.Page,
PageSize: result.PageSize,
})
}
// sessionListResponse is the body of GetSessionsByTenant.
type sessionListResponse struct {
Success bool `json:"success"`
Data []*types.SessionListItem `json:"data"`
Total int64 `json:"total" extensions:"x-agent"`
Page int `json:"page" extensions:"x-agent"`
PageSize int `json:"page_size" extensions:"x-agent"`
}
// UpdateSession godoc
// @Summary 更新会话
// @Description 更新会话属性
// @Tags 会话
// @Accept json
// @Produce json
// @Param id path string true "会话ID"
// @Param request body types.Session true "会话信息"
// @Success 200 {object} map[string]interface{} "更新后的会话"
// @Failure 404 {object} errors.AppError "会话不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{id} [put]
func (h *Handler) UpdateSession(c *gin.Context) {
ctx := c.Request.Context()
// Get session ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Verify tenant ID from context for authorization
tenantID, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
logger.Error(ctx, "Failed to get tenant ID")
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
// Parse request body to session object
var session types.Session
if err := c.ShouldBindJSON(&session); err != nil {
logger.Error(ctx, "Failed to parse session data", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
session.ID = id
session.TenantID = tenantID.(uint64)
// Call service to update session
if err := h.sessionService.UpdateSession(ctx, &session); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "Session not found, ID: %s", id)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Reload session from database to return complete timestamps and stored fields
updatedSession, err := h.sessionService.GetSession(ctx, id)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Return updated session
logger.Infof(ctx, "Session updated successfully, ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": updatedSession,
})
}
// DeleteSession godoc
// @Summary 删除会话
// @Description 删除指定的会话
// @Tags 会话
// @Accept json
// @Produce json
// @Param id path string true "会话ID"
// @Success 200 {object} map[string]interface{} "删除成功"
// @Failure 404 {object} errors.AppError "会话不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{id} [delete]
func (h *Handler) DeleteSession(c *gin.Context) {
ctx := c.Request.Context()
// Get session ID from URL parameter
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Call service to delete session
if err := h.sessionService.DeleteSession(ctx, id); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "Session not found, ID: %s", id)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
h.browserSkill.Forget(browserSkillScope(ctx), []string{id})
// Return success message
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Session deleted successfully",
})
}
// ClearSessionMessages godoc
// @Summary 清空会话消息
// @Description 删除会话中的所有消息,同时清除 LLM 上下文和聊天历史知识库条目。会话本身保留。
// @Tags 会话
// @Accept json
// @Produce json
// @Param id path string true "会话ID"
// @Success 200 {object} map[string]interface{} "清空成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "会话不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{id}/messages [delete]
func (h *Handler) ClearSessionMessages(c *gin.Context) {
ctx := c.Request.Context()
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
logger.Infof(ctx, "Clearing all messages for session: %s", id)
if err := h.messageService.ClearSessionMessages(ctx, id); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "Session not found, ID: %s", id)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": id})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Session messages cleared successfully, ID: %s", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Session messages cleared successfully",
})
}
// batchDeleteRequest represents the request body for batch deleting sessions
type batchDeleteRequest struct {
IDs []string `json:"ids"`
DeleteAll bool `json:"delete_all"`
}
// BatchDeleteSessions godoc
// @Summary 批量删除会话
// @Description 根据ID列表批量删除对话会话,或设置 delete_all=true 删除当前空间的所有会话
// @Tags 会话
// @Accept json
// @Produce json
// @Param request body batchDeleteRequest true "批量删除请求"
// @Success 200 {object} map[string]interface{} "删除结果"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/batch [delete]
func (h *Handler) BatchDeleteSessions(c *gin.Context) {
ctx := c.Request.Context()
var req batchDeleteRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Errorf(ctx, "Invalid batch delete request: %v", err)
c.Error(errors.NewBadRequestError("invalid request"))
return
}
if req.DeleteAll {
if err := h.sessionService.DeleteAllSessions(ctx); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
h.browserSkill.ForgetAll(browserSkillScope(ctx))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "All sessions deleted successfully",
})
return
}
if len(req.IDs) == 0 {
c.Error(errors.NewBadRequestError("ids are required when delete_all is false"))
return
}
// Sanitize all IDs
sanitizedIDs := make([]string, 0, len(req.IDs))
for _, id := range req.IDs {
sanitized := secutils.SanitizeForLog(id)
if sanitized != "" {
sanitizedIDs = append(sanitizedIDs, sanitized)
}
}
if len(sanitizedIDs) == 0 {
c.Error(errors.NewBadRequestError("no valid session IDs provided"))
return
}
if err := h.sessionService.BatchDeleteSessions(ctx, sanitizedIDs); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "No visible sessions found for batch delete")
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
h.browserSkill.Forget(browserSkillScope(ctx), sanitizedIDs)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Sessions deleted successfully",
})
}
// PinSession godoc
// @Summary 置顶会话
// @Description 将指定会话置顶(用户维度)
// @Tags 会话
// @Produce json
// @Param session_id path string true "会话ID"
// @Success 200 {object} map[string]interface{} "置顶成功"
// @Failure 404 {object} errors.AppError "会话不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/pin [post]
func (h *Handler) PinSession(c *gin.Context) {
h.setSessionPinned(c, true)
}
// UnpinSession godoc
// @Summary 取消置顶会话
// @Description 取消指定会话的置顶
// @Tags 会话
// @Produce json
// @Param id path string true "会话ID"
// @Success 200 {object} map[string]interface{} "取消置顶成功"
// @Failure 404 {object} errors.AppError "会话不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{id}/pin [delete]
func (h *Handler) UnpinSession(c *gin.Context) {
h.setSessionPinned(c, false)
}
func (h *Handler) setSessionPinned(c *gin.Context, pinned bool) {
ctx := c.Request.Context()
// POST and DELETE for /sessions/.../pin register under different wildcards
// (POST :session_id, DELETE :id — see router.go). Accept whichever is set.
rawID := c.Param("session_id")
if rawID == "" {
rawID = c.Param("id")
}
id := secutils.SanitizeForLog(rawID)
if id == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
rows, err := h.sessionService.SetSessionPinned(ctx, id, pinned)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": id,
"pinned": pinned,
})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Zero rows means the session doesn't exist or isn't visible to this user;
// tell the client rather than reporting success.
if rows == 0 {
c.Error(errors.NewNotFoundError(errors.ErrSessionNotFound.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"is_pinned": pinned,
})
}
// SetCollaborationStopper persists stops independently of the live stream owner.
func (h *Handler) SetCollaborationStopper(stop func(context.Context, string, string) error) {
h.stopCollaboration = stop
}
+524
View File
@@ -0,0 +1,524 @@
package session
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"academy/internal/event"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// convertImageAttachments converts ImageAttachment slice to types.MessageImages
func convertImageAttachments(items []ImageAttachment) types.MessageImages {
if len(items) == 0 {
return nil
}
result := make(types.MessageImages, len(items))
for i, item := range items {
result[i] = types.MessageImage{
URL: item.URL,
Caption: item.Caption,
}
}
return result
}
// extractImageURLsAndOCRText extracts image references and concatenated analysis text.
// For LLM consumption it prefers the raw Data (data URI) when available so that
// image_resolve can skip the disk round-trip; falls back to the storage URL otherwise.
func extractImageURLsAndOCRText(images []ImageAttachment) (urls []string, ocrText string) {
if len(images) == 0 {
return nil, ""
}
urls = make([]string, 0, len(images))
var parts []string
for _, img := range images {
switch {
case img.Data != "":
urls = append(urls, img.Data)
case img.URL != "":
urls = append(urls, img.URL)
}
if img.Caption != "" {
parts = append(parts, img.Caption)
}
}
if len(parts) > 0 {
ocrText = strings.Join(parts, "\n")
}
return
}
// convertMentionedItems converts MentionedItemRequest slice to types.MentionedItems
func convertMentionedItems(items []MentionedItemRequest) types.MentionedItems {
if len(items) == 0 {
return nil
}
result := make(types.MentionedItems, len(items))
for i, item := range items {
result[i] = types.MentionedItem{
ID: item.ID,
Name: item.Name,
Type: item.Type,
KBType: item.KBType,
KBID: item.KBID,
KBName: item.KBName,
ServiceID: item.ServiceID,
SkillName: item.SkillName,
}
}
return result
}
func tagScopesFromMentionedItems(items []MentionedItemRequest) []types.TagScope {
byKB := make(map[string][]string)
seen := make(map[string]map[string]bool)
for _, item := range items {
if item.Type != "tag" || item.ID == "" || item.KBID == "" {
continue
}
if seen[item.KBID] == nil {
seen[item.KBID] = make(map[string]bool)
}
if seen[item.KBID][item.ID] {
continue
}
seen[item.KBID][item.ID] = true
byKB[item.KBID] = append(byKB[item.KBID], item.ID)
}
scopes := make([]types.TagScope, 0, len(byKB))
for kbID, tagIDs := range byKB {
scopes = append(scopes, types.TagScope{KnowledgeBaseID: kbID, TagIDs: tagIDs})
}
return scopes
}
// orphanTagIDsForScope returns tag IDs from the request that are not already
// covered by scoped mentions.
func orphanTagIDsForScope(tagIDs []string, scopes []types.TagScope) []string {
if len(tagIDs) == 0 {
return nil
}
covered := make(map[string]bool)
for _, scope := range scopes {
for _, id := range scope.TagIDs {
covered[id] = true
}
}
orphan := make([]string, 0, len(tagIDs))
for _, id := range tagIDs {
if id != "" && !covered[id] {
orphan = append(orphan, id)
}
}
return orphan
}
// validateUnscopedTagIDs rejects bare tag_ids that cannot be attached to a KB.
func validateUnscopedTagIDs(orphan []string, kbIDs []string) error {
if len(orphan) == 0 {
return nil
}
if len(kbIDs) == 1 {
return nil
}
return fmt.Errorf("tag_ids must be scoped via mentioned_items or exactly one knowledge_base_id")
}
// mergeTagScopesFromRequestIDs supplements tag scopes built from mentioned_items
// with bare tag_ids when the client did not send kb_id on each tag mention.
// Orphan tag IDs are attached to the sole knowledge_base_id when unambiguous.
func mergeTagScopesFromRequestIDs(scopes []types.TagScope, tagIDs, kbIDs []string) []types.TagScope {
orphan := orphanTagIDsForScope(tagIDs, scopes)
if len(orphan) == 0 {
return scopes
}
if len(kbIDs) != 1 {
return scopes
}
kbID := kbIDs[0]
for i, scope := range scopes {
if scope.KnowledgeBaseID == kbID {
merged := append(append([]string(nil), scope.TagIDs...), orphan...)
scopes[i].TagIDs = dedupRequestStrings(merged)
return scopes
}
}
return append(scopes, types.TagScope{KnowledgeBaseID: kbID, TagIDs: dedupRequestStrings(orphan)})
}
func mentionedIDsByType(items []MentionedItemRequest, itemType string) []string {
seen := make(map[string]bool)
result := make([]string, 0)
for _, item := range items {
if item.Type != itemType || item.ID == "" || seen[item.ID] {
continue
}
seen[item.ID] = true
result = append(result, item.ID)
}
return result
}
func dedupRequestStrings(values []string) []string {
seen := make(map[string]bool, len(values))
result := make([]string, 0, len(values))
for _, value := range values {
if value == "" || seen[value] {
continue
}
seen[value] = true
result = append(result, value)
}
return result
}
// setSSEHeaders sets the standard Server-Sent Events headers
func setSSEHeaders(c *gin.Context) {
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("X-Accel-Buffering", "no")
}
// buildStreamResponse constructs a StreamResponse from a StreamEvent
func buildStreamResponse(evt interfaces.StreamEvent, requestID string) *types.StreamResponse {
response := &types.StreamResponse{
ID: requestID,
ResponseType: evt.Type,
Content: evt.Content,
Done: evt.Done,
Data: evt.Data,
Usage: evt.Usage,
}
// Extract session_id and assistant_message_id for agent_query events
if evt.Type == types.ResponseTypeAgentQuery {
if sid, ok := evt.Data["session_id"].(string); ok {
response.SessionID = sid
}
if amid, ok := evt.Data["assistant_message_id"].(string); ok {
response.AssistantMessageID = amid
}
}
// Special handling for references event
if evt.Type == types.ResponseTypeReferences {
refsData := evt.Data["references"]
if refsData == nil {
return response
}
if refs, ok := refsData.(types.References); ok {
response.KnowledgeReferences = refs
} else if refs, ok := refsData.([]*types.SearchResult); ok {
response.KnowledgeReferences = types.References(refs)
} else if refs, ok := refsData.([]interface{}); ok {
// Handle case where data was serialized/deserialized (e.g., from Redis)
searchResults := make([]*types.SearchResult, 0, len(refs))
for _, ref := range refs {
if refMap, ok := ref.(map[string]interface{}); ok {
searchResults = append(searchResults, searchResultFromMap(refMap))
}
}
response.KnowledgeReferences = types.References(searchResults)
}
}
return response
}
// sendCompletionEvent sends a final completion event to the client
// NOTE: This is now a no-op because:
// 1. The 'complete' event from handleComplete already signals stream completion
// 2. Sending an extra empty 'answer' event with done:true causes frontend issues
// (multiple done events can confuse state management)
//
// The frontend should use 'complete' response_type to detect stream completion
func sendCompletionEvent(c *gin.Context, requestID string) {
// Intentionally empty - completion is signaled by the 'complete' event
// which is already sent before this function is called
}
// createAgentQueryEvent creates a standard agent query event.
// It carries the persisted user/assistant timestamps so the live UI can
// display the same created_at that history reload will return.
func createAgentQueryEvent(
sessionID, assistantMessageID, userMessageID string,
userCreatedAt, assistantCreatedAt time.Time,
) interfaces.StreamEvent {
data := map[string]interface{}{
"session_id": sessionID,
"assistant_message_id": assistantMessageID,
}
if userMessageID != "" {
data["user_message_id"] = userMessageID
}
if !userCreatedAt.IsZero() {
data["user_created_at"] = userCreatedAt.UTC().Format(time.RFC3339Nano)
}
if !assistantCreatedAt.IsZero() {
data["assistant_created_at"] = assistantCreatedAt.UTC().Format(time.RFC3339Nano)
}
return interfaces.StreamEvent{
ID: fmt.Sprintf("query-%d", time.Now().UnixNano()),
Type: types.ResponseTypeAgentQuery,
Content: "",
Done: true,
Timestamp: time.Now(),
Data: data,
}
}
// createUserMessage creates a user message and returns the created message.
func (h *Handler) createUserMessage(ctx context.Context, sessionID, query, requestID string, mentionedItems types.MentionedItems, images types.MessageImages, attachments types.MessageAttachments, channel string, attribution *types.SuggestionAttribution) (*types.Message, error) {
return h.messageService.CreateMessage(ctx, &types.Message{
SessionID: sessionID,
Role: "user",
Content: query,
RequestID: requestID,
CreatedAt: time.Now(),
IsCompleted: true,
MentionedItems: mentionedItems,
Images: images,
Attachments: attachments,
Channel: channel,
ExecutionContext: types.MessageExecutionContext{SuggestionAttribution: attribution},
})
}
// createAssistantMessage creates an assistant message
func (h *Handler) createAssistantMessage(ctx context.Context, assistantMessage *types.Message) (*types.Message, error) {
assistantMessage.CreatedAt = time.Now()
return h.messageService.CreateMessage(ctx, assistantMessage)
}
// setupStreamHandler creates and subscribes a stream handler
func (h *Handler) setupStreamHandler(
ctx context.Context,
sessionID, assistantMessageID, requestID string,
tenantID uint64,
receivedAt time.Time,
assistantMessage *types.Message,
eventBus *event.EventBus,
) *AgentStreamHandler {
streamHandler := NewAgentStreamHandler(
ctx, sessionID, assistantMessageID, requestID, tenantID, receivedAt,
assistantMessage, h.streamManager, eventBus, h.artifactCollector,
h.workspaceCheckpointer, h.sandboxIDLookup,
)
streamHandler.Subscribe()
return streamHandler
}
// setupStopEventHandler registers a stop event handler
func (h *Handler) setupStopEventHandler(
eventBus *event.EventBus,
sessionID string,
sessionTenantID uint64,
assistantMessage *types.Message,
cancel context.CancelFunc,
) {
eventBus.On(event.EventStop, func(ctx context.Context, evt event.Event) error {
logger.Infof(ctx, "Received stop event, cancelling async operations for session: %s", sessionID)
cancel()
// Preserve whatever has been streamed so far; do not overwrite Content.
// Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent).
// Use WithoutCancel so the GORM UPDATE survives the upcoming ctx.Done triggered by cancel()/client disconnect.
updateCtx := context.WithValue(
context.WithoutCancel(ctx),
types.TenantIDContextKey, sessionTenantID,
)
h.completeAssistantMessage(updateCtx, assistantMessage, "", "") // empty query: stopped conversations are not indexed
return nil
})
}
// stopWatcherMaxDuration bounds the lifetime of a stop watcher as an
// anti-leak backstop. Normally the watcher exits well before this on a
// terminal stream event; this only guards pathological streams that never
// emit a terminal marker.
const stopWatcherMaxDuration = 2 * time.Hour
// startStopWatcher polls the stream for a user-requested stop event
// independently of the client's SSE connection.
//
// Background: the original design only detected the stop marker inside
// handleAgentEventsForSSE, which is bound to the request context. Once the
// client closes the SSE stream (common for API-Key / programmatic callers that
// close the stream before POSTing /stop), that loop returns and nothing
// converts the stop marker (written to the shared StreamManager by
// StopSession) into a context cancellation — so generation keeps running to
// completion even though /stop returned success.
//
// The watcher is intentionally self-terminating rather than tied to the QA
// service call returning: KnowledgeQA (quick answer) returns immediately while
// the actual token stream runs in a background goroutine, whereas AgentQA
// (smart reasoning) blocks until done. Keying teardown off the call return
// would therefore tear the watcher down before quick-answer streaming even
// starts. Instead it exits when it observes a terminal stream event
// (complete, or a stream-level error), on stop, or after a safety timeout.
func (h *Handler) startStopWatcher(
ctx context.Context,
sessionID, assistantMessageID string,
eventBus *event.EventBus,
) {
go func() {
watchCtx, cancel := context.WithTimeout(ctx, stopWatcherMaxDuration)
defer cancel()
ticker := time.NewTicker(300 * time.Millisecond)
defer ticker.Stop()
offset := 0
for {
select {
case <-watchCtx.Done():
return
case <-ticker.C:
events, newOffset, err := h.streamManager.GetEvents(watchCtx, sessionID, assistantMessageID, offset)
if err != nil {
// Transient read error (e.g. Redis blip); retry next tick.
continue
}
offset = newOffset
for _, evt := range events {
switch {
case evt.Type == types.ResponseType(event.EventStop):
logger.Infof(watchCtx,
"Stop watcher detected stop event, cancelling generation for session=%s, message=%s",
sessionID, assistantMessageID)
eventBus.Emit(watchCtx, event.Event{
Type: event.EventStop,
SessionID: sessionID,
Data: event.StopData{
SessionID: sessionID,
MessageID: assistantMessageID,
Reason: "user_requested",
},
})
return
case evt.Type == types.ResponseTypeComplete:
// Generation finished normally; nothing left to stop.
return
case evt.Type == types.ResponseTypeError && evt.Done:
// Stream-level (terminal) error; generation has ended.
return
}
}
}
}
}()
}
// writeAgentQueryEvent writes an agent query event to the stream manager
func (h *Handler) writeAgentQueryEvent(
ctx context.Context,
sessionID, userMessageID string,
userCreatedAt time.Time,
assistantMessage *types.Message,
resume *types.AgentResume,
) {
assistantMessageID := ""
var assistantCreatedAt time.Time
if assistantMessage != nil {
assistantMessageID = assistantMessage.ID
assistantCreatedAt = assistantMessage.CreatedAt
}
agentQueryEvent := createAgentQueryEvent(
sessionID, assistantMessageID, userMessageID, userCreatedAt, assistantCreatedAt,
)
if resume != nil && resume.Prompt != nil {
agentQueryEvent.Data["resume_pending_id"] = resume.Prompt.ID
agentQueryEvent.Data["resume_tool_call_id"] = resume.Prompt.ToolCallID
}
if err := h.streamManager.AppendEvent(ctx, sessionID, assistantMessageID, agentQueryEvent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"message_id": assistantMessageID,
})
// Non-fatal error, continue
}
}
// Helper function for type assertion with default value
func getString(m map[string]interface{}, key string) string {
if val, ok := m[key].(string); ok {
return val
}
return ""
}
func getFloat64(m map[string]interface{}, key string) float64 {
if val, ok := m[key].(float64); ok {
return val
}
if val, ok := m[key].(int); ok {
return float64(val)
}
return 0.0
}
// searchResultFromMap rebuilds a *types.SearchResult from a map that went
// through JSON/Redis serialization, preserving all fields including metadata.
func searchResultFromMap(refMap map[string]interface{}) *types.SearchResult {
sr := &types.SearchResult{
ID: getString(refMap, "id"),
Content: getString(refMap, "content"),
KnowledgeID: getString(refMap, "knowledge_id"),
ChunkIndex: int(getFloat64(refMap, "chunk_index")),
KnowledgeTitle: getString(refMap, "knowledge_title"),
StartAt: int(getFloat64(refMap, "start_at")),
EndAt: int(getFloat64(refMap, "end_at")),
Seq: int(getFloat64(refMap, "seq")),
Score: getFloat64(refMap, "score"),
ChunkType: getString(refMap, "chunk_type"),
ParentChunkID: getString(refMap, "parent_chunk_id"),
ImageInfo: getString(refMap, "image_info"),
KnowledgeFilename: getString(refMap, "knowledge_filename"),
KnowledgeSource: getString(refMap, "knowledge_source"),
KnowledgeChannel: getString(refMap, "knowledge_channel"),
KnowledgeDescription: getString(refMap, "knowledge_description"),
KnowledgeCustomMetadata: getString(refMap, "knowledge_custom_metadata"),
MatchedContent: getString(refMap, "matched_content"),
KnowledgeBaseID: getString(refMap, "knowledge_base_id"),
}
if meta, ok := refMap["metadata"].(map[string]interface{}); ok {
metadata := make(map[string]string)
for k, v := range meta {
if strVal, ok := v.(string); ok {
metadata[k] = strVal
}
}
sr.Metadata = metadata
}
if raw, ok := refMap["source_locators"]; ok && raw != nil {
if b, err := json.Marshal(raw); err == nil {
var locators types.SourceLocators
if json.Unmarshal(b, &locators) == nil {
sr.SourceLocators = locators
}
}
}
if raw, ok := refMap["matched_images"]; ok && raw != nil {
if b, err := json.Marshal(raw); err == nil {
var images []types.MatchedImage
if json.Unmarshal(b, &images) == nil {
sr.MatchedImages = images
}
}
}
return sr
}
// createDefaultSummaryConfig and fillSummaryConfigDefaults used to build
// per-session SummaryConfig from tenant-level ConversationConfig + config.yaml
// defaults. Both helpers became unreachable when the chat pipeline moved to
// CustomAgent (builtin-quick-answer / smart-reasoning) and the tenant-level
// ConversationConfig field was removed; deleting them avoids the only
// remaining references to that defunct path.
+167
View File
@@ -0,0 +1,167 @@
package session
import (
"context"
"encoding/json"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTagScopesFromMentionedItems(t *testing.T) {
scopes := tagScopesFromMentionedItems([]MentionedItemRequest{
{Type: "tag", ID: "tag-1", KBID: "kb-1"},
{Type: "tag", ID: "tag-2", KBID: "kb-1"},
{Type: "tag", ID: "tag-3", KBID: "kb-2"},
{Type: "tag", ID: "orphan", KBID: ""},
})
assert.Len(t, scopes, 2)
byKB := make(map[string][]string)
for _, scope := range scopes {
byKB[scope.KnowledgeBaseID] = scope.TagIDs
}
assert.ElementsMatch(t, []string{"tag-1", "tag-2"}, byKB["kb-1"])
assert.Equal(t, []string{"tag-3"}, byKB["kb-2"])
}
func TestMergeTagScopesFromRequestIDs_SingleKB(t *testing.T) {
scopes := mergeTagScopesFromRequestIDs(
[]types.TagScope{{KnowledgeBaseID: "kb-1", TagIDs: []string{"tag-1"}}},
[]string{"tag-2"},
[]string{"kb-1"},
)
assert.Len(t, scopes, 1)
assert.ElementsMatch(t, []string{"tag-1", "tag-2"}, scopes[0].TagIDs)
}
func TestMergeTagScopesFromRequestIDs_OrphanWithSingleKB(t *testing.T) {
scopes := mergeTagScopesFromRequestIDs(nil, []string{"tag-9"}, []string{"kb-1"})
assert.Len(t, scopes, 1)
assert.Equal(t, "kb-1", scopes[0].KnowledgeBaseID)
assert.Equal(t, []string{"tag-9"}, scopes[0].TagIDs)
}
func TestMergeTagScopesFromRequestIDs_AmbiguousKBIgnored(t *testing.T) {
scopes := mergeTagScopesFromRequestIDs(nil, []string{"tag-9"}, []string{"kb-1", "kb-2"})
assert.Empty(t, scopes)
}
func TestValidateUnscopedTagIDs(t *testing.T) {
assert.NoError(t, validateUnscopedTagIDs(nil, nil))
assert.NoError(t, validateUnscopedTagIDs(nil, []string{"kb-1", "kb-2"}))
assert.NoError(t, validateUnscopedTagIDs([]string{"tag-9"}, []string{"kb-1"}))
assert.Error(t, validateUnscopedTagIDs([]string{"tag-9"}, []string{"kb-1", "kb-2"}))
assert.Error(t, validateUnscopedTagIDs([]string{"tag-9"}, nil))
}
// TestSearchResultFromMap_RoundTrip simulates the Redis round trip: a
// *types.SearchResult is serialized to JSON, deserialized into a generic map,
// and rebuilt via searchResultFromMap. All fields, including metadata, must
// survive.
func TestSearchResultFromMap_RoundTrip(t *testing.T) {
original := &types.SearchResult{
ID: "chunk-1",
Content: "first part\nsecond part",
KnowledgeID: "knowledge-1",
ChunkIndex: 3,
KnowledgeTitle: "title",
StartAt: 10,
EndAt: 20,
Seq: 2,
Score: 4.5,
ChunkType: "text",
ParentChunkID: "parent-1",
ImageInfo: `[{"url":"cdn.example.com"}]`,
KnowledgeFilename: "doc.txt",
KnowledgeSource: "upload",
KnowledgeChannel: "api",
KnowledgeDescription: "desc",
KnowledgeCustomMetadata: "course_url: https://example.com/course\nlesson_url: https://example.com/lesson",
MatchedContent: "matched question",
KnowledgeBaseID: "kb-1",
Metadata: map[string]string{"page": "3"},
MatchedImages: []types.MatchedImage{
{ChunkID: "image-1", KnowledgeBaseID: "kb-1", URL: "resource://image"},
},
SourceLocators: types.SourceLocators{
{Type: types.SourceLocatorPDF, Page: 4, BBox: []float64{0.1, 0.2, 0.9, 0.3}, Quote: "q"},
},
}
raw, err := json.Marshal(original)
require.NoError(t, err)
var refMap map[string]interface{}
require.NoError(t, json.Unmarshal(raw, &refMap))
got := searchResultFromMap(refMap)
assert.Equal(t, original.ID, got.ID)
assert.Equal(t, original.Content, got.Content)
assert.Equal(t, original.KnowledgeID, got.KnowledgeID)
assert.Equal(t, original.ChunkIndex, got.ChunkIndex)
assert.Equal(t, original.KnowledgeTitle, got.KnowledgeTitle)
assert.Equal(t, original.StartAt, got.StartAt)
assert.Equal(t, original.EndAt, got.EndAt)
assert.Equal(t, original.Seq, got.Seq)
assert.Equal(t, original.Score, got.Score)
assert.Equal(t, original.ChunkType, got.ChunkType)
assert.Equal(t, original.ParentChunkID, got.ParentChunkID)
assert.Equal(t, original.ImageInfo, got.ImageInfo)
assert.Equal(t, original.MatchedImages, got.MatchedImages)
assert.Equal(t, original.KnowledgeFilename, got.KnowledgeFilename)
assert.Equal(t, original.KnowledgeSource, got.KnowledgeSource)
assert.Equal(t, original.KnowledgeDescription, got.KnowledgeDescription)
assert.Equal(t, original.KnowledgeChannel, got.KnowledgeChannel)
assert.Equal(t, original.KnowledgeCustomMetadata, got.KnowledgeCustomMetadata)
assert.Equal(t, original.MatchedContent, got.MatchedContent)
assert.Equal(t, original.KnowledgeBaseID, got.KnowledgeBaseID)
assert.Equal(t, original.Metadata, got.Metadata)
assert.Equal(t, original.SourceLocators, got.SourceLocators)
}
func TestCreateAgentQueryEventIncludesPersistedTimestamps(t *testing.T) {
userAt := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
assistantAt := time.Date(2026, 1, 2, 3, 4, 6, 0, time.UTC)
evt := createAgentQueryEvent("sess-1", "asst-1", "user-1", userAt, assistantAt)
assert.Equal(t, types.ResponseTypeAgentQuery, evt.Type)
assert.Equal(t, "sess-1", evt.Data["session_id"])
assert.Equal(t, "asst-1", evt.Data["assistant_message_id"])
assert.Equal(t, "user-1", evt.Data["user_message_id"])
assert.Equal(t, userAt.Format(time.RFC3339Nano), evt.Data["user_created_at"])
assert.Equal(t, assistantAt.Format(time.RFC3339Nano), evt.Data["assistant_created_at"])
}
func TestCreateAgentQueryEventOmitsZeroTimestamps(t *testing.T) {
evt := createAgentQueryEvent("sess-1", "asst-1", "", time.Time{}, time.Time{})
_, hasUserID := evt.Data["user_message_id"]
_, hasUserAt := evt.Data["user_created_at"]
_, hasAssistantAt := evt.Data["assistant_created_at"]
assert.False(t, hasUserID)
assert.False(t, hasUserAt)
assert.False(t, hasAssistantAt)
}
func TestQueryEventMarksApprovalResumeGeneration(t *testing.T) {
resumes := []*types.AgentResume{nil, {Prompt: &types.AgentPrompt{ID: "approval", ToolCallID: "blocked"}}}
for _, resume := range resumes {
recorder := &completionEventRecorder{}
h := &Handler{streamManager: recorder}
h.writeAgentQueryEvent(
context.Background(), "session", "user", time.Time{}, &types.Message{ID: "answer"}, resume,
)
require.Len(t, recorder.events, 1)
data := recorder.events[0].Data
if resume == nil {
require.NotContains(t, data, "resume_pending_id")
} else {
require.Equal(t, "approval", data["resume_pending_id"])
require.Equal(t, "blocked", data["resume_tool_call_id"])
}
}
}
@@ -0,0 +1,144 @@
package session
import (
"context"
"errors"
"testing"
"time"
"academy/internal/application/access"
"academy/internal/event"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type imageCompletionMessages struct {
interfaces.MessageService
saved *types.Message
tenant uint64
err error
beforeSave func()
}
func (s *imageCompletionMessages) UpdateMessage(ctx context.Context, message *types.Message) error {
if err := ctx.Err(); err != nil {
return err
}
if s.beforeSave != nil {
s.beforeSave()
}
if s.err != nil {
return s.err
}
s.tenant = types.MustTenantIDFromContext(ctx)
snapshot := *message
s.saved = &snapshot
return nil
}
func TestQuickAnswerCompletionPersistsAfterGenerationCancellation(t *testing.T) {
messages := &imageCompletionMessages{}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
message := &types.Message{
ID: "m", SessionID: "s", Role: "assistant", Content: "already streamed answer", AgentTenantID: 2,
}
ctx, cancel := context.WithCancel(types.WithExecutionTenant(context.Background(), 1))
streamHandler := h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), message, bus)
cancel()
released := false
h.completeQuickAnswerTurn(ctx, &sseStreamContext{
eventBus: bus, streamHandler: streamHandler, assistantMessage: message,
releaseTurn: func() { released = true },
}, "", "")
require.NotNil(t, messages.saved)
require.Equal(t, "already streamed answer", messages.saved.Content)
require.Equal(t, uint64(1), messages.tenant)
require.True(t, released)
require.Equal(t, types.ResponseTypeComplete, stream.events[len(stream.events)-1].Type)
}
type imageCompletionStream struct {
completionEventRecorder
onComplete func()
}
func (s *imageCompletionStream) AppendEvent(
ctx context.Context, session, message string, e interfaces.StreamEvent,
) error {
if e.Type == types.ResponseTypeComplete && s.onComplete != nil {
s.onComplete()
}
return s.completionEventRecorder.AppendEvent(ctx, session, message, e)
}
func TestSharedImageCompletionWaitsForPersistedReferences(t *testing.T) {
const image = "resource://AbCdEfGhIjKlMnOpQrStUv"
for _, quick := range []bool{false, true} {
name := "agent"
if quick {
name = "quick answer"
}
t.Run(name, func(t *testing.T) {
for _, fail := range []bool{false, true} {
t.Run(map[bool]string{false: "saved", true: "save failed"}[fail], func(t *testing.T) {
messages := &imageCompletionMessages{}
if fail {
messages.err = errors.New("database unavailable")
}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
message := &types.Message{
ID: "m", SessionID: "s", Role: "assistant", AgentTenantID: 2,
}
// Execution uses the host workspace; the conversation belongs to
// the visitor's workspace and must be saved there before notifying it.
runCtx := types.WithExecutionTenant(context.Background(), 2)
saveCtx := types.WithExecutionTenant(runCtx, 1)
streamHandler := h.setupStreamHandler(runCtx, "s", "m", "req", 1, time.Now(), message, bus)
streamCtx := &sseStreamContext{
eventBus: bus, streamHandler: streamHandler, assistantMessage: message,
}
completed := 0
stream.onComplete = func() {
completed++
require.NotNil(t, messages.saved, "a completion-triggered image GET must see persisted output")
require.True(t, access.MessageReferencesFile(messages.saved, image))
require.True(t, messages.saved.IsCompleted)
require.Equal(t, uint64(1), messages.tenant)
}
messages.beforeSave = func() {
require.Zero(t, completed, "completion must not escape while the database write is pending")
}
answer := "![host image](" + image + ")"
if quick {
message.Content = answer
h.completeQuickAnswerTurn(saveCtx, streamCtx, "", "")
} else {
require.NoError(t, bus.Emit(runCtx, event.Event{
Type: event.EventAgentComplete,
Data: event.AgentCompleteData{MessageID: "m", FinalAnswer: answer},
}))
require.Zero(t, completed)
h.completeStreamAssistantMessage(saveCtx, streamCtx, "", "")
}
last := stream.events[len(stream.events)-1]
if fail {
require.Zero(t, completed)
require.Equal(t, types.ResponseTypeError, last.Type)
require.Equal(t, "message_persistence", last.Data["stage"])
} else {
require.Equal(t, 1, completed)
require.Equal(t, types.ResponseTypeComplete, last.Type)
require.Equal(t, answer, last.Data["final_content"])
require.NoError(t, streamHandler.publishCompletion(saveCtx))
require.Equal(t, 1, completed, "completion must only be published once")
}
})
}
})
}
}
+169
View File
@@ -0,0 +1,169 @@
package session
import (
"context"
"encoding/base64"
"fmt"
"strings"
filesvc "academy/internal/application/service/file"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/google/uuid"
)
const (
maxImageSize = 10 << 20 // 10MB per image
maxImagesCount = 5
)
// saveImageAttachments decodes base64 images from the request and saves them to
// storage. The images slice is mutated in place: URL is populated.
// This is always called when images are present. VLM analysis is handled
// separately (either in the pipeline rewrite step for RAG paths, or via
// analyzeImageAttachments for pure chat paths with non-vision models).
func (h *Handler) saveImageAttachments(ctx context.Context, images []ImageAttachment, tenantID uint64, storageProvider string) error {
if len(images) == 0 {
return nil
}
if len(images) > maxImagesCount {
return fmt.Errorf("too many images, max %d", maxImagesCount)
}
fileSvc := h.resolveImageFileService(ctx, storageProvider)
for i := range images {
img := &images[i]
if img.Data == "" {
continue
}
imgBytes, ext, err := decodeDataURI(img.Data)
if err != nil {
return fmt.Errorf("decode image %d: %w", i, err)
}
if len(imgBytes) > maxImageSize {
return fmt.Errorf("image %d too large (%d bytes, max %d)", i, len(imgBytes), maxImageSize)
}
storedName := fmt.Sprintf("chat-images/%s%s", uuid.New().String(), ext)
fileURL, err := fileSvc.SaveBytes(ctx, imgBytes, tenantID, storedName, false)
if err != nil {
return fmt.Errorf("save image %d: %w", i, err)
}
img.URL = fileURL
}
return nil
}
// analyzeImageAttachments runs VLM analysis on saved images and populates Caption.
// Used as a fallback for pure chat paths where the pipeline rewrite step won't run.
// For RAG paths, image analysis is handled in the pipeline rewrite step instead.
func (h *Handler) analyzeImageAttachments(ctx context.Context, images []ImageAttachment, vlmModelID string, userQuery string) {
if len(images) == 0 || vlmModelID == "" {
return
}
vlmModel, err := h.modelService.GetVLMModel(ctx, vlmModelID)
if err != nil {
logger.Warnf(ctx, "No VLM model available for image analysis, skipping: %v", err)
return
}
for i := range images {
img := &images[i]
if img.Data == "" {
continue
}
imgBytes, _, decErr := decodeDataURI(img.Data)
if decErr != nil {
logger.Warnf(ctx, "Failed to decode image %d for VLM analysis: %v", i, decErr)
continue
}
prompt := buildImageAnalysisPrompt(userQuery)
analysis, analysisErr := vlmModel.Predict(ctx, [][]byte{imgBytes}, prompt)
if analysisErr != nil {
logger.Warnf(ctx, "VLM analysis failed for image %d: %v", i, analysisErr)
} else {
img.Caption = analysis
}
}
}
// buildImageAnalysisPrompt generates a context-aware VLM prompt based on the
// user's question. Instead of doing generic OCR + Caption separately, we do a
// single analysis call that is tailored to the user's intent.
func buildImageAnalysisPrompt(userQuery string) string {
if strings.TrimSpace(userQuery) == "" {
return "请分析这张图片的内容。如果包含文字,请提取关键文字信息;如果是自然图片,请描述其主要内容。用简洁的中文回答。"
}
return fmt.Sprintf(
"用户的问题是:%s\n\n请分析图片中与用户问题相关的内容。"+
"如果图片包含文字/文档/表格,请提取与问题相关的关键信息。"+
"如果是自然图片/截图/图表,请描述与问题相关的视觉内容。"+
"用简洁的中文回答,只输出分析结果。",
userQuery,
)
}
func decodeDataURI(dataURI string) ([]byte, string, error) {
if !strings.HasPrefix(dataURI, "data:") {
return nil, "", fmt.Errorf("not a data URI")
}
idx := strings.Index(dataURI, ";base64,")
if idx < 0 {
return nil, "", fmt.Errorf("unsupported data URI encoding (expected base64)")
}
mimeType := dataURI[5:idx]
decoded, err := base64.StdEncoding.DecodeString(dataURI[idx+8:])
if err != nil {
return nil, "", fmt.Errorf("base64 decode: %w", err)
}
ext := mimeToExt(mimeType)
return decoded, ext, nil
}
func mimeToExt(mime string) string {
switch strings.ToLower(mime) {
case "image/png":
return ".png"
case "image/jpeg":
return ".jpg"
case "image/gif":
return ".gif"
case "image/webp":
return ".webp"
default:
return ".png"
}
}
func (h *Handler) resolveImageFileService(ctx context.Context, storageProvider string) interfaces.FileService {
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
return h.fileService
}
if h.storageResolver != nil {
svc, resolvedProvider, err := h.storageResolver.ResolveFileService(ctx, tenant, "", storageProvider, "")
if err == nil && svc != nil {
logger.Infof(ctx, "[image-storage] using storage instance provider=%s for image uploads", resolvedProvider)
return svc
}
if err != nil {
logger.Warnf(ctx, "[image-storage] failed to resolve storage instance for provider=%s: %v", storageProvider, err)
}
}
if strings.TrimSpace(storageProvider) == "" || tenant.StorageEngineConfig == nil {
return h.fileService
}
svc, resolvedProvider, err := filesvc.NewFileServiceFromStorageConfig(storageProvider, tenant.StorageEngineConfig, "")
if err != nil {
logger.Warnf(ctx, "[image-storage] failed to create %s file service: %v, fallback to default", storageProvider, err)
return h.fileService
}
logger.Infof(ctx, "[image-storage] using provider=%s for image uploads", resolvedProvider)
return svc
}
+47
View File
@@ -0,0 +1,47 @@
package session
import (
"net/http"
"net/http/httptest"
"testing"
"academy/internal/middleware"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestCreateSessionKind(t *testing.T) {
for _, tc := range []struct {
body, kind string
status int
}{
{`{}`, "", http.StatusCreated},
{`{"kind":"assistant"}`, types.SessionKindAssistant, http.StatusCreated},
{`{"kind":""}`, "", http.StatusCreated},
{`{"kind":"other"}`, "", http.StatusBadRequest},
{`{"kind":"Assistant"}`, "", http.StatusBadRequest},
{`{"kind":" assistant "}`, "", http.StatusBadRequest},
} {
t.Run(tc.body, func(t *testing.T) {
h := handlerWithApprovedDirs()
response := postSession(t, h, tc.body)
require.Equal(t, tc.status, response.Code)
if tc.status == http.StatusCreated {
require.Equal(t, tc.kind, h.created.Kind)
} else {
require.Nil(t, h.created)
}
})
}
}
func TestListSessionsRejectsInvalidKind(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(middleware.ErrorHandler())
router.GET("/sessions", (&Handler{}).GetSessionsByTenant)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/sessions?kind=other", nil))
require.Equal(t, http.StatusBadRequest, response.Code)
}
@@ -0,0 +1,25 @@
package session
import (
"testing"
"github.com/stretchr/testify/require"
"academy/internal/types"
)
// knowledge-search runs one search per scoped target and reranks every
// candidate, so result counts are bounded.
func TestKnowledgeSearchOptionsBoundsCounts(t *testing.T) {
t.Parallel()
_, err := knowledgeSearchOptions(&SearchKnowledgeRequest{MatchCount: types.MaxRequestedResults})
require.NoError(t, err)
_, err = knowledgeSearchOptions(&SearchKnowledgeRequest{MatchCount: types.MaxRequestedResults + 1})
require.ErrorContains(t, err, "match_count must not exceed")
_, err = knowledgeSearchOptions(&SearchKnowledgeRequest{
Rerank: &types.RerankOptions{TopK: types.MaxRequestedResults + 1},
})
require.ErrorContains(t, err, "rerank.top_k must not exceed")
}
@@ -0,0 +1,28 @@
package session
import (
"testing"
"academy/internal/stream"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestSetupSSEStreamPropagatesBusinessSession(t *testing.T) {
for _, mode := range []qaMode{qaModeNormal, qaModeAgent} {
h := &Handler{streamManager: stream.NewMemoryStreamManager()}
reqCtx := &qaRequestContext{
c: newSteerWiringGinContext(),
ctx: types.WithSessionID(t.Context(), "parent-session"),
sessionID: "business-session",
session: &types.Session{ID: "business-session"},
assistantMessage: &types.Message{ID: "assistant", SessionID: "business-session"},
}
streamCtx := h.setupSSEStream(reqCtx, false, mode)
require.NotNil(t, streamCtx)
id, ok := types.SessionIDFromContext(streamCtx.asyncCtx)
require.True(t, ok)
require.Equal(t, reqCtx.session.ID, id)
streamCtx.cancel()
}
}
+56
View File
@@ -0,0 +1,56 @@
package session
import (
"path/filepath"
"strings"
)
// HostProjectDirsLoader returns the user-approved project directories from
// desktop prefs. Nil means no directory is approved.
type HostProjectDirsLoader func() []string
func (h *Handler) approvedDirs() []string {
if h == nil || h.approvedProjectDirs == nil {
return nil
}
return h.approvedProjectDirs()
}
// MatchApprovedDir reports whether raw names a directory the user approved
// through the native picker, returning it cleaned.
//
// This is the authorization boundary for host workspaces, so it lives here
// rather than in localsandbox: session create runs in every edition, and the
// desktop-only sandbox must not be imported by cmd/server.
//
// Matching is exact after Clean. A subdirectory of an approved directory is
// not approved: the user picked a root, and honouring children would let a
// stored value reach deeper than the picker ever offered.
func MatchApprovedDir(raw string, approved []string) (string, bool) {
raw = strings.TrimSpace(raw)
if raw == "" || !filepath.IsAbs(raw) {
return "", false
}
cleaned := filepath.Clean(raw)
for _, dir := range approved {
dir = strings.TrimSpace(dir)
if dir == "" {
continue
}
if filepath.Clean(dir) == cleaned {
return cleaned, true
}
}
return "", false
}
// bindHostWorkspaceDir accepts an omitted/empty project_dir as unbound. A
// non-empty value must be an absolute path already on the approved list
// (compared after Clean). The stored value is the cleaned path.
func bindHostWorkspaceDir(raw string, approved []string) (string, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", true
}
return MatchApprovedDir(raw, approved)
}
@@ -0,0 +1,38 @@
package session
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestMatchApprovedDirAcceptsOnlyApprovedAbsolutePaths(t *testing.T) {
approved := []string{"/Users/dev/My Project", " /Users/dev/Other/ ", ""}
got, ok := MatchApprovedDir("/Users/dev/My Project", approved)
require.True(t, ok)
require.Equal(t, "/Users/dev/My Project", got)
got, ok = MatchApprovedDir(" /Users/dev/My Project/ ", approved)
require.True(t, ok, "trailing separator and padding must still match")
require.Equal(t, "/Users/dev/My Project", got)
got, ok = MatchApprovedDir("/Users/dev/Other", approved)
require.True(t, ok, "an approved entry is cleaned before comparison")
require.Equal(t, "/Users/dev/Other", got)
for _, bad := range []string{
"",
"relative/dir",
"/Users/dev/My Project/nested",
"/Users/dev/Unapproved",
} {
_, ok := MatchApprovedDir(bad, approved)
require.False(t, ok, bad)
}
}
func TestMatchApprovedDirRejectsEverythingWithoutApprovals(t *testing.T) {
_, ok := MatchApprovedDir("/Users/dev/My Project", nil)
require.False(t, ok)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,62 @@
package session
import (
"encoding/base64"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func encodedAttachment(data string, declaredSize int64) AttachmentUpload {
return AttachmentUpload{
Data: base64.StdEncoding.EncodeToString([]byte(data)),
FileName: "file.txt",
FileSize: declaredSize,
}
}
func TestDecodeAndValidateAttachmentUploadsUsesActualBytes(t *testing.T) {
uploads := []AttachmentUpload{encodedAttachment("123456", 1)}
_, err := decodeAndValidateAttachmentUploads(uploads, 5, 5, 100)
require.Error(t, err)
assert.Contains(t, err.Error(), "exceeds size limit")
}
func TestDecodeAndValidateAttachmentUploadsBoundsCountAndTotal(t *testing.T) {
t.Run("count", func(t *testing.T) {
uploads := make([]AttachmentUpload, 6)
for i := range uploads {
uploads[i] = encodedAttachment("x", 1)
}
_, err := decodeAndValidateAttachmentUploads(uploads, 5, 10, 100)
require.Error(t, err)
assert.Contains(t, err.Error(), "at most 5")
})
t.Run("total", func(t *testing.T) {
uploads := []AttachmentUpload{
encodedAttachment(strings.Repeat("a", 6), 6),
encodedAttachment(strings.Repeat("b", 6), 6),
}
_, err := decodeAndValidateAttachmentUploads(uploads, 5, 10, 10)
require.Error(t, err)
assert.Contains(t, err.Error(), "total request limit")
})
}
func TestDecodeAndValidateAttachmentUploadsReturnsDecodedBytes(t *testing.T) {
decoded, err := decodeAndValidateAttachmentUploads(
[]AttachmentUpload{encodedAttachment("hello", 999)},
5,
10,
10,
)
require.NoError(t, err)
require.Len(t, decoded, 1)
assert.Equal(t, []byte("hello"), decoded[0])
}
@@ -0,0 +1,173 @@
package session
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type queryValidationSessionStub struct {
interfaces.SessionService
lookupCalls int
}
func (s *queryValidationSessionStub) GetOwnedSession(context.Context, string) (*types.Session, error) {
s.lookupCalls++
return nil, errors.New("stop at session lookup")
}
func TestQAQueryValidation(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
query string
rejectBeforeLookup bool
}{
{name: "empty", rejectBeforeLookup: true},
{name: "whitespace", query: " \t\r\n ", rejectBeforeLookup: true},
{name: "unicode whitespace", query: "\u3000\u00a0", rejectBeforeLookup: true},
{name: "null byte", query: "hello\x00world", rejectBeforeLookup: true},
{name: "escape character", query: "hello\x1bworld", rejectBeforeLookup: true},
{name: "script element", query: "<script>alert(1)</script>"},
{name: "event handler", query: `<img src=x onerror="alert(1)">`},
{name: "script URL", query: "javascript:alert(1)"},
{name: "agent frontend snippet", query: `Why doesn't my <button onclick="save()">Save</button> fire?`},
{name: "agent javascript snippet", query: "What does javascript:void(0) do?"},
{name: "English", query: "What is retrieval augmented generation?"},
{name: "Unicode", query: "请解释厄尔尼诺现象 🌊"},
{name: "multiline", query: "Compare:\n\tGo\r\n\tPython"},
{name: "padded text", query: " Explain retrieval.\n"},
}
for _, endpoint := range []string{"knowledge-chat", "agent-chat"} {
t.Run(endpoint, func(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sessions := &queryValidationSessionStub{}
h := &Handler{sessionService: sessions}
router := gin.New()
router.Use(middleware.ErrorHandler())
router.POST("/knowledge-chat/:session_id", h.KnowledgeQA)
router.POST("/agent-chat/:session_id", h.AgentQA)
body, err := json.Marshal(CreateKnowledgeQARequest{Query: tt.query})
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "/"+endpoint+"/session-1", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if tt.rejectBeforeLookup {
assert.Equal(t, http.StatusBadRequest, response.Code, response.Body.String())
assert.Contains(t, response.Header().Get("Content-Type"), "application/json")
assert.Zero(t, sessions.lookupCalls, "reject the query before session lookup or QA work")
} else {
// Stop at a controlled not-found response: valid queries must
// reach the ordinary session lookup without invoking a model.
assert.Equal(t, http.StatusNotFound, response.Code, response.Body.String())
assert.Equal(t, 1, sessions.lookupCalls)
}
})
}
})
}
}
func TestQAQueryValidationAcceptsUploadWithoutText(t *testing.T) {
gin.SetMode(gin.TestMode)
image := []ImageAttachment{{Data: "data:image/png;base64,aGk="}}
tests := []struct {
name string
body CreateKnowledgeQARequest
rejectBeforeLookup bool
}{
{name: "image only", body: CreateKnowledgeQARequest{Images: image}},
{name: "whitespace with image", body: CreateKnowledgeQARequest{Query: " \n", Images: image}},
{
name: "attachment upload only",
body: CreateKnowledgeQARequest{AttachmentUploads: []AttachmentUpload{{Data: "aGk=", FileName: "a.txt"}}},
},
{
name: "url-only image",
body: CreateKnowledgeQARequest{Images: []ImageAttachment{{URL: "http://127.0.0.1/a.png"}}},
rejectBeforeLookup: true,
},
// Pre-uploaded documents may still fail or time out after the stream
// starts, leaving the turn with no content to answer from.
{
name: "attachment id only",
body: CreateKnowledgeQARequest{AttachmentIDs: []string{"doc-1"}},
rejectBeforeLookup: true,
},
}
for _, endpoint := range []string{"knowledge-chat", "agent-chat"} {
t.Run(endpoint, func(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sessions := &queryValidationSessionStub{}
h := &Handler{sessionService: sessions}
router := gin.New()
router.Use(middleware.ErrorHandler())
router.POST("/knowledge-chat/:session_id", h.KnowledgeQA)
router.POST("/agent-chat/:session_id", h.AgentQA)
body, err := json.Marshal(tt.body)
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "/"+endpoint+"/session-1", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if tt.rejectBeforeLookup {
assert.Equal(t, http.StatusBadRequest, response.Code, response.Body.String())
assert.Zero(t, sessions.lookupCalls)
} else {
assert.Equal(t, http.StatusNotFound, response.Code, response.Body.String())
assert.Equal(t, 1, sessions.lookupCalls)
}
})
}
})
}
}
func TestPersistTurnMessagesStoresWhatTheUserTyped(t *testing.T) {
msgs := &steerPersistingMessageStub{}
h := &Handler{messageService: msgs}
question := types.UploadOnlyQuestion("zh-CN")
reqCtx := &qaRequestContext{
sessionID: "sess-1",
query: question,
images: []ImageAttachment{{Data: "data:image/png;base64,aGk=", URL: "resource://img"}},
assistantMessage: &types.Message{SessionID: "sess-1", Role: "assistant"},
}
require.NoError(t, h.persistTurnMessages(context.Background(), reqCtx))
stored := msgs.byID[reqCtx.userMessageID]
require.NotNil(t, stored)
assert.Empty(t, stored.Content, "an image-only message must not gain text the user never typed")
assert.Len(t, stored.Images, 1)
assert.Equal(t, question, reqCtx.buildQARequest().Query)
}
func TestUploadOnlyQuery(t *testing.T) {
image := &CreateKnowledgeQARequest{Images: []ImageAttachment{{Data: "data:image/png;base64,aGk="}}}
zh := context.WithValue(context.Background(), types.LanguageContextKey, "zh-CN")
en := context.WithValue(context.Background(), types.LanguageContextKey, "en-US")
assert.Equal(t, "请根据我上传的内容回答。", uploadOnlyQuery(zh, image))
assert.Equal(t, "Please answer based on what I uploaded.", uploadOnlyQuery(en, image))
assert.Empty(t, uploadOnlyQuery(zh, &CreateKnowledgeQARequest{}))
assert.Empty(t, uploadOnlyQuery(zh, &CreateKnowledgeQARequest{Images: []ImageAttachment{{URL: "http://x/a.png"}}}))
}
@@ -0,0 +1,78 @@
package session
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestQAReasoningEffortValidation(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, endpoint := range []string{"knowledge-chat", "agent-chat"} {
for _, effort := range []string{"", "off", "auto", "high", "max", "unknown"} {
t.Run(endpoint+"/"+effort, func(t *testing.T) {
sessions := &queryValidationSessionStub{}
h := &Handler{sessionService: sessions}
router := gin.New()
router.Use(middleware.ErrorHandler())
router.POST("/knowledge-chat/:session_id", h.KnowledgeQA)
router.POST("/agent-chat/:session_id", h.AgentQA)
body, err := json.Marshal(CreateKnowledgeQARequest{Query: "question", ReasoningEffort: effort})
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "/"+endpoint+"/session", bytes.NewReader(body))
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if effort == "unknown" {
require.Equal(t, http.StatusBadRequest, response.Code)
require.Contains(t, response.Body.String(), "reasoning_effort")
require.Zero(t, sessions.lookupCalls)
} else {
require.Equal(t, 1, sessions.lookupCalls)
}
})
}
}
}
type reasoningSessionStub struct {
interfaces.SessionService
state *types.SessionLastRequestState
}
func (s *reasoningSessionStub) UpdateSessionLastRequestState(
_ context.Context, _ string, state *types.SessionLastRequestState,
) error {
s.state = state
return nil
}
func TestQAReasoningEffortPropagationAndRestore(t *testing.T) {
for _, effort := range []string{"", "off", "high"} {
t.Run(effort, func(t *testing.T) {
rc := &qaRequestContext{
sessionID: "session", session: &types.Session{ID: "session"},
assistantMessage: &types.Message{ID: "answer"}, reasoningEffort: effort,
}
require.Equal(t, effort, rc.buildQARequest().ReasoningEffort)
sessions := &reasoningSessionStub{}
h := &Handler{sessionService: sessions}
h.persistLastRequestState(context.Background(), rc, qaModeAgent)
require.NotNil(t, sessions.state)
raw, err := sessions.state.Value()
require.NoError(t, err)
var restored types.SessionLastRequestState
require.NoError(t, restored.Scan(raw))
require.Equal(t, effort, restored.ReasoningEffort)
})
}
}
@@ -0,0 +1,83 @@
package session
import (
"context"
"testing"
"time"
"academy/internal/logger"
"academy/internal/sandbox/admission"
"academy/internal/stream"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func setupLeaseTestStream(ctx context.Context, t *testing.T, mode qaMode) *sseStreamContext {
t.Helper()
h := &Handler{streamManager: stream.NewMemoryStreamManager()}
req := &qaRequestContext{
ctx: ctx,
skipSSE: true,
sessionID: "session",
session: &types.Session{ID: "session", TenantID: 42},
assistantMessage: &types.Message{ID: "assistant", SessionID: "session"},
}
if mode == qaModeAgent {
req.customAgent = &types.CustomAgent{ID: "agent"}
}
got := h.setupSSEStream(req, false, mode)
t.Cleanup(got.cancel)
return got
}
func TestSetupSSEStreamCancelsOnTurnLeaseLoss(t *testing.T) {
for name, mode := range map[string]qaMode{"normal": qaModeNormal, "agent": qaModeAgent} {
for _, lostBeforeSetup := range []bool{false, true} {
t.Run(name+map[bool]string{false: "/during-run", true: "/before-setup"}[lostBeforeSetup],
func(t *testing.T) {
requestCtx, disconnect := context.WithCancel(t.Context())
defer disconnect()
// The handler detaches from HTTP before acquiring the turn lease.
baseCtx := logger.CloneContext(requestCtx)
reg := admission.NewMemory()
scope := admission.MachineScope("machine")
member := admission.SessionMember("session", "turn", "token")
lease, err := reg.Hold(baseCtx, scope, member, admission.DefaultHoldTTL)
require.NoError(t, err)
defer lease.Release()
turnCtx, endTurn := admission.Bind(baseCtx, lease)
defer endTurn()
turnCtx = context.WithValue(turnCtx, types.SandboxAdmissionExemptContextKey, []string{member})
if lostBeforeSetup {
reg.ExpireMember(scope, member)
require.Eventually(t, func() bool { return turnCtx.Err() != nil },
time.Second, time.Millisecond)
}
got := setupLeaseTestStream(turnCtx, t, mode)
require.Equal(t, []string{member}, got.asyncCtx.Value(types.SandboxAdmissionExemptContextKey))
if lostBeforeSetup {
require.ErrorIs(t, context.Cause(got.asyncCtx), admission.ErrLeaseLost)
} else {
disconnect()
require.NoError(t, got.asyncCtx.Err(), "HTTP disconnect must not stop the detached turn")
reg.ExpireMember(scope, member)
}
require.Eventually(t, func() bool { return got.asyncCtx.Err() != nil },
time.Second, time.Millisecond,
"the actual QA context must stop when the turn loses its admission")
require.ErrorIs(t, context.Cause(got.asyncCtx), admission.ErrLeaseLost)
})
}
}
}
func TestSetupSSEStreamKeepsOrdinaryCancellationDetached(t *testing.T) {
parent, cancel := context.WithCancel(t.Context())
cancel()
got := setupLeaseTestStream(parent, t, qaModeNormal)
require.Never(t, func() bool { return got.asyncCtx.Err() != nil }, 30*time.Millisecond, time.Millisecond,
"ordinary request cancellation is not a lost sandbox lease")
got.cancel()
require.ErrorIs(t, got.asyncCtx.Err(), context.Canceled, "explicit stop must still cancel QA")
}
@@ -0,0 +1,122 @@
package session
import (
"context"
"testing"
"time"
"academy/internal/event"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func newQuickAnswerFailureHarness(
t *testing.T, msg *types.Message,
) (*sseStreamContext, *imageCompletionMessages, *imageCompletionStream, *bool) {
t.Helper()
messages := &imageCompletionMessages{}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
ctx := types.WithExecutionTenant(context.Background(), 1)
streamHandler := h.setupStreamHandler(ctx, msg.SessionID, msg.ID, "req", 1, time.Now(), msg, bus)
released := false
streamCtx := &sseStreamContext{
eventBus: bus,
streamHandler: streamHandler,
assistantMessage: msg,
releaseTurn: func() { released = true },
}
h.registerQuickAnswerFailureHandler(streamCtx, new(bool), 1)
return streamCtx, messages, stream, &released
}
const testStreamError = `create chat completion: Post "https://model.example:9999/v1/chat/completions": EOF`
// A failed quick-answer turn must persist the error text, complete the
// assistant row, release the turn lease and close the SSE stream with a
// completion event. Without this the row stayed empty and incomplete: the
// live UI showed the error, but a refresh rendered a blank bubble (issue
// #4145).
func TestQuickAnswerFailurePersistsErrorAndCompletesTurn(t *testing.T) {
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
streamCtx, messages, stream, released := newQuickAnswerFailureHarness(t, msg)
require.NoError(t, streamCtx.eventBus.Emit(context.Background(), event.Event{
Type: event.EventError,
Data: event.ErrorData{
Error: testStreamError,
Stage: "chat_completion_stream",
SessionID: "s",
},
}))
require.NotNil(t, messages.saved)
require.Equal(t, testStreamError, messages.saved.Content)
require.True(t, messages.saved.IsCompleted)
require.Equal(t, uint64(1), messages.tenant)
require.True(t, *released)
require.NotEmpty(t, stream.events)
require.Equal(t, types.ResponseTypeError, stream.events[0].Type)
require.Equal(t, testStreamError, stream.events[0].Content)
require.True(t, stream.events[0].Done)
last := stream.events[len(stream.events)-1]
require.Equal(t, types.ResponseTypeComplete, last.Type)
}
// A stream that produced partial text before failing keeps it; the error is
// appended instead of replacing the answer.
func TestQuickAnswerFailureAppendsErrorToPartialAnswer(t *testing.T) {
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant", Content: "partial answer"}
streamCtx, messages, _, released := newQuickAnswerFailureHarness(t, msg)
require.NoError(t, streamCtx.eventBus.Emit(context.Background(), event.Event{
Type: event.EventError,
Data: event.ErrorData{Error: "stream ended early", Stage: "chat_completion_stream"},
}))
require.NotNil(t, messages.saved)
require.Equal(t, "partial answer\n\nstream ended early", messages.saved.Content)
require.True(t, messages.saved.IsCompleted)
require.True(t, *released)
}
// After the turn already completed (e.g. a fallback answer), a late error
// event must not re-complete or overwrite the saved answer.
func TestQuickAnswerFailureAfterCompletionIsIgnored(t *testing.T) {
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
messages := &imageCompletionMessages{}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
ctx := types.WithExecutionTenant(context.Background(), 1)
h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), msg, bus)
streamCtx := &sseStreamContext{eventBus: bus, assistantMessage: msg}
handled := true
h.registerQuickAnswerFailureHandler(streamCtx, &handled, 1)
require.NoError(t, bus.Emit(ctx, event.Event{
Type: event.EventError,
Data: event.ErrorData{Error: "late failure", Stage: "chat_completion_stream"},
}))
require.Nil(t, messages.saved)
require.Equal(t, "", msg.Content)
}
// An error event carrying no message still completes the turn, with a
// non-empty explanation instead of a blank answer.
func TestQuickAnswerFailureWithEmptyErrorUsesFallbackText(t *testing.T) {
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
streamCtx, messages, _, released := newQuickAnswerFailureHarness(t, msg)
require.NoError(t, streamCtx.eventBus.Emit(context.Background(), event.Event{
Type: event.EventError,
Data: event.ErrorData{Stage: "knowledge_qa_execution"},
}))
require.NotNil(t, messages.saved)
require.Equal(t, quickAnswerFailureContent, messages.saved.Content)
require.True(t, messages.saved.IsCompleted)
require.True(t, *released)
}
@@ -0,0 +1,134 @@
package session
import (
"context"
"sync"
"time"
"academy/internal/event"
"academy/internal/types"
)
// quickAnswerTimelineTools are the stages a fast-answer turn draws on its
// timeline. A turn that retrieved nothing still reports the search it ran, so
// the set is what decides whether the step survives a reload — not whether it
// produced citations. Keep in sync with RAG_TIMELINE_TOOL_NAMES on the frontend.
var quickAnswerTimelineTools = map[string]struct{}{
"query_understand": {},
"knowledge_search": {},
"attachment_parsing": {},
"image_analysis": {},
}
// quickAnswerTimelineRecorder persists the fast-answer pipeline's timeline into
// the assistant message's AgentSteps.
//
// Reconstructing the timeline from knowledge_references only works for turns
// that cited something: a turn that searched and found nothing, or that only
// parsed an attachment, came back from history with no steps at all and lost
// the timeline it had while streaming.
type quickAnswerTimelineRecorder struct {
mu sync.Mutex
msg *types.Message
pending map[string]map[string]any
startedAt map[string]time.Time
}
// registerQuickAnswerTimelineRecorder subscribes to the pipeline's tool events
// for the lifetime of one fast-answer turn. Agent mode is excluded on purpose:
// its own steps are written by the agent stream handler, which overwrites
// AgentSteps wholesale.
func registerQuickAnswerTimelineRecorder(bus *event.EventBus, msg *types.Message) {
if bus == nil || msg == nil {
return
}
rec := &quickAnswerTimelineRecorder{
msg: msg,
pending: make(map[string]map[string]any),
startedAt: make(map[string]time.Time),
}
bus.On(event.EventAgentToolCall, rec.onToolCall)
bus.On(event.EventAgentToolResult, rec.onToolResult)
}
func (r *quickAnswerTimelineRecorder) onToolCall(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentToolCallData)
if !ok || !isQuickAnswerTimelineTool(data.ToolName) || data.ToolCallID == "" {
return nil
}
r.mu.Lock()
defer r.mu.Unlock()
r.pending[data.ToolCallID] = data.Arguments
r.startedAt[data.ToolCallID] = time.Now()
return nil
}
// onToolResult is where the step is persisted. Waiting for the result keeps a
// half-finished stage out of history: a stage still running when the turn is
// stopped would come back from a reload looking like it had completed.
func (r *quickAnswerTimelineRecorder) onToolResult(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentToolResultData)
if !ok || !isQuickAnswerTimelineTool(data.ToolName) || data.ToolCallID == "" {
return nil
}
r.mu.Lock()
defer r.mu.Unlock()
args := r.pending[data.ToolCallID]
delete(r.pending, data.ToolCallID)
started, hasStart := r.startedAt[data.ToolCallID]
delete(r.startedAt, data.ToolCallID)
duration := data.Duration
if duration == 0 && hasStart {
duration = time.Since(started).Milliseconds()
}
appendQuickAnswerToolCall(r.msg, types.ToolCall{
ID: types.PipelineToolCallIDPrefix + data.ToolCallID,
Name: data.ToolName,
Args: args,
Result: &types.ToolResult{
Success: data.Success,
Output: data.Output,
Error: data.Error,
Data: data.Data,
},
Duration: duration,
})
return nil
}
func isQuickAnswerTimelineTool(name string) bool {
_, ok := quickAnswerTimelineTools[name]
return ok
}
// ensureQuickAnswerStep returns the single step a fast-answer turn records
// into. There is no ReAct loop here, so everything belongs to iteration 0.
func ensureQuickAnswerStep(msg *types.Message) *types.AgentStep {
if len(msg.AgentSteps) == 0 {
msg.AgentSteps = types.AgentSteps{{
Iteration: 0,
Timestamp: time.Now(),
ToolCalls: make([]types.ToolCall, 0),
}}
}
return &msg.AgentSteps[0]
}
func appendQuickAnswerToolCall(msg *types.Message, call types.ToolCall) {
step := ensureQuickAnswerStep(msg)
for i := range step.ToolCalls {
if step.ToolCalls[i].ID == call.ID {
step.ToolCalls[i] = call
return
}
}
step.ToolCalls = append(step.ToolCalls, call)
}
func markQuickAnswerTruncated(msg *types.Message) {
ensureQuickAnswerStep(msg).Truncated = true
}
@@ -0,0 +1,162 @@
package session
import (
"context"
"encoding/json"
"testing"
"time"
"academy/internal/event"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func emitTimelineStage(
t *testing.T,
bus *event.EventBus,
toolCallID, toolName string,
args map[string]any,
result event.AgentToolResultData,
) {
t.Helper()
require.NoError(t, bus.Emit(context.Background(), event.Event{
Type: event.EventAgentToolCall,
Data: event.AgentToolCallData{ToolCallID: toolCallID, ToolName: toolName, Arguments: args},
}))
result.ToolCallID = toolCallID
result.ToolName = toolName
require.NoError(t, bus.Emit(context.Background(), event.Event{
Type: event.EventAgentToolResult,
Data: result,
}))
}
// A turn that searched and cited nothing is exactly the case history replay
// could not reconstruct from knowledge_references, so it must be persisted.
func TestQuickAnswerTimelineRecorderPersistsSearchWithoutResults(t *testing.T) {
bus := event.NewEventBus()
msg := &types.Message{}
registerQuickAnswerTimelineRecorder(bus, msg)
emitTimelineStage(t, bus, "call-1", "knowledge_search",
map[string]any{"query": "你好", "search_source": "knowledge"},
event.AgentToolResultData{
Output: "未检索到相关内容",
Success: true,
Duration: 12,
Data: map[string]interface{}{"count": 0, "doc_count": 0, "web_count": 0},
})
require.Len(t, msg.AgentSteps, 1)
require.Len(t, msg.AgentSteps[0].ToolCalls, 1)
call := msg.AgentSteps[0].ToolCalls[0]
assert.Equal(t, "knowledge_search", call.Name)
assert.Equal(t, types.PipelineToolCallIDPrefix+"call-1", call.ID)
assert.Equal(t, "你好", call.Args["query"])
require.NotNil(t, call.Result)
assert.True(t, call.Result.Success)
assert.Equal(t, "未检索到相关内容", call.Result.Output)
assert.Equal(t, 0, call.Result.Data["count"])
assert.Equal(t, int64(12), call.Duration)
}
func TestQuickAnswerTimelineRecorderKeepsStageOrderAndIgnoresOtherTools(t *testing.T) {
bus := event.NewEventBus()
msg := &types.Message{}
registerQuickAnswerTimelineRecorder(bus, msg)
emitTimelineStage(t, bus, "call-1", "query_understand", nil,
event.AgentToolResultData{Output: "已完成问题理解", Success: true})
emitTimelineStage(t, bus, "call-2", "web_search", nil,
event.AgentToolResultData{Output: "ignored", Success: true})
emitTimelineStage(t, bus, "call-3", "knowledge_search", nil,
event.AgentToolResultData{Output: "检索到 3 条相关内容", Success: true})
require.Len(t, msg.AgentSteps, 1)
names := make([]string, 0, len(msg.AgentSteps[0].ToolCalls))
for _, call := range msg.AgentSteps[0].ToolCalls {
names = append(names, call.Name)
}
assert.Equal(t, []string{"query_understand", "knowledge_search"}, names)
}
// A stage that never reported a result belongs to an interrupted turn. Keeping
// it out of history is what stops a reload from showing it as completed.
func TestQuickAnswerTimelineRecorderSkipsStagesWithoutResult(t *testing.T) {
bus := event.NewEventBus()
msg := &types.Message{}
registerQuickAnswerTimelineRecorder(bus, msg)
require.NoError(t, bus.Emit(context.Background(), event.Event{
Type: event.EventAgentToolCall,
Data: event.AgentToolCallData{ToolCallID: "call-1", ToolName: "knowledge_search"},
}))
assert.Empty(t, msg.AgentSteps)
}
// Reasoning and timeline stages share one step, so neither may clobber the other.
func TestQuickAnswerReasoningAndTimelineShareOneStep(t *testing.T) {
bus := event.NewEventBus()
msg := &types.Message{}
registerQuickAnswerTimelineRecorder(bus, msg)
appendQuickAnswerReasoning(msg, "思考中")
emitTimelineStage(t, bus, "call-1", "knowledge_search", nil,
event.AgentToolResultData{Output: "未检索到相关内容", Success: true})
appendQuickAnswerReasoning(msg, "继续")
require.Len(t, msg.AgentSteps, 1)
assert.Equal(t, "思考中继续", msg.AgentSteps[0].ReasoningContent)
require.Len(t, msg.AgentSteps[0].ToolCalls, 1)
}
func TestQuickAnswerTruncationPersistsOnSharedStep(t *testing.T) {
msg := &types.Message{}
appendQuickAnswerReasoning(msg, "思考中")
markQuickAnswerTruncated(msg)
require.Len(t, msg.AgentSteps, 1)
assert.Equal(t, "思考中", msg.AgentSteps[0].ReasoningContent)
assert.True(t, msg.AgentSteps[0].Truncated)
}
// Verify the durable completion boundary, including the message update and
// JSON reload, independently of the provider's stream generation.
func TestQuickAnswerFallbackTruncationSurvivesCompletion(t *testing.T) {
for _, content := range []string{"output budget exhausted", "partial answer"} {
t.Run(content, func(t *testing.T) {
messages := &imageCompletionMessages{}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant", Content: content, IsFallback: true}
appendQuickAnswerReasoning(msg, "reasoning")
markQuickAnswerTruncated(msg)
ctx := types.WithExecutionTenant(context.Background(), 1)
handler := h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), msg, bus)
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "fallback", Type: event.EventAgentFinalAnswer,
Data: event.AgentFinalAnswerData{Content: content, Done: true, IsFallback: true, Truncated: true},
}))
require.NotEmpty(t, stream.events)
require.Equal(t, true, stream.events[0].Data["truncated"])
require.Equal(t, true, stream.events[0].Data["is_fallback"])
h.completeQuickAnswerTurn(ctx, &sseStreamContext{
eventBus: bus, streamHandler: handler, assistantMessage: msg,
}, "", "")
require.NotNil(t, messages.saved)
raw, err := json.Marshal(messages.saved)
require.NoError(t, err)
var restored types.Message
require.NoError(t, json.Unmarshal(raw, &restored))
require.Equal(t, content, restored.Content)
require.True(t, restored.IsFallback)
require.True(t, restored.IsCompleted)
require.Len(t, restored.AgentSteps, 1)
require.True(t, restored.AgentSteps[0].Truncated)
require.Equal(t, "reasoning", restored.AgentSteps[0].ReasoningContent)
})
}
}
@@ -0,0 +1,261 @@
package session
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/service"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type resolveAgentShareStub struct {
agent *types.CustomAgent
err error
}
func (s *resolveAgentShareStub) GetSharedAgentForTenant(
_ context.Context,
_ uint64,
_ types.TenantRole,
_ string,
_ ...uint64,
) (*types.CustomAgent, error) {
return s.agent, s.err
}
func (s *resolveAgentShareStub) ShareAgent(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) RemoveShare(context.Context, string, string, uint64) error {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharesByAgent(context.Context, string, uint64) ([]*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharesByOrganization(context.Context, string) ([]*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharedAgents(context.Context, uint64, types.TenantRole) ([]*types.SharedAgentInfo, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharedAgentsInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) ListSharedAgentsInOrganizations(context.Context, []string, uint64, types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) SetSharedAgentDisabledByMe(context.Context, uint64, string, uint64, bool) error {
panic("not implemented")
}
func (s *resolveAgentShareStub) TenantCanAccessKBViaSomeSharedAgent(context.Context, uint64, types.TenantRole, *types.KnowledgeBase) (bool, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) GetShare(context.Context, string) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) GetShareByAgentAndOrg(context.Context, string, string) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) GetShareByAgentIDForTenant(context.Context, uint64, string, uint64) (*types.AgentShare, error) {
panic("not implemented")
}
func (s *resolveAgentShareStub) CountByOrganizations(context.Context, []string) (map[string]int64, error) {
panic("not implemented")
}
type resolveOwnAgentStub struct {
agent *types.CustomAgent
err error
}
func (s *resolveOwnAgentStub) GetAgentByID(context.Context, string) (*types.CustomAgent, error) {
return s.agent, s.err
}
func (s *resolveOwnAgentStub) CreateAgent(context.Context, *types.CustomAgent) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) GetAgentByIDAndTenant(context.Context, string, uint64) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) ListAgents(context.Context) ([]*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) UpdateAgent(
context.Context, *types.CustomAgent, *string,
) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) DeleteAgent(context.Context, string) error {
panic("not implemented")
}
func (s *resolveOwnAgentStub) CopyAgent(context.Context, string) (*types.CustomAgent, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) GetSuggestedQuestions(context.Context, string, []string, []string, []types.TagScope, int) ([]types.SuggestedQuestion, error) {
panic("not implemented")
}
func (s *resolveOwnAgentStub) GetKnowledgeSuggestedQuestions(context.Context, string, []string, []string, []types.TagScope, int) ([]types.SuggestedQuestion, error) {
panic("not implemented")
}
func newResolveAgentTestContext(tenantID uint64) (*gin.Context, context.Context) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
c.Set(types.UserIDContextKey.String(), "user-1")
c.Set(types.TenantIDContextKey.String(), tenantID)
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID)
c.Request = c.Request.WithContext(ctx)
return c, ctx
}
func TestResolveAgent_RejectsInvalidSharedSelectorWithoutLocalFallback(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
localAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7, Name: "Local"}
h := &Handler{
agentShareService: &resolveAgentShareStub{},
customAgentService: &resolveOwnAgentStub{agent: localAgent},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 84)
require.Nil(t, agent)
require.Equal(t, uint64(0), effectiveTenantID)
require.False(t, sharedReadOnly)
}
func TestResolveAgent_UsesSharedAgentWhenSourceSelectorMatches(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
sharedAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 84, Name: "Shared"}
h := &Handler{
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7}},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 84)
require.Equal(t, sharedAgent, agent)
require.Equal(t, uint64(84), effectiveTenantID)
require.True(t, sharedReadOnly)
}
func TestResolveAgent_FallsBackToLocalAgentWithoutSourceSelector(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
localAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7, Name: "Local"}
h := &Handler{
agentShareService: &resolveAgentShareStub{},
customAgentService: &resolveOwnAgentStub{agent: localAgent},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 0)
require.Equal(t, localAgent, agent)
require.Equal(t, uint64(0), effectiveTenantID)
require.False(t, sharedReadOnly)
}
// Built-in IDs exist in every workspace. Without a source selector a share of
// the same ID must not replace the caller's own agent.
func TestResolveAgent_PrefersOwnAgentOverSameIDShareWithoutSourceSelector(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
localAgent := &types.CustomAgent{ID: "builtin-quick-answer", TenantID: 7, Name: "Local"}
h := &Handler{
agentShareService: &resolveAgentShareStub{
agent: &types.CustomAgent{ID: "builtin-quick-answer", TenantID: 84, Name: "Shared"},
},
customAgentService: &resolveOwnAgentStub{agent: localAgent},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-quick-answer", 0)
require.Equal(t, localAgent, agent)
require.Equal(t, uint64(0), effectiveTenantID)
require.False(t, sharedReadOnly)
}
// A shared agent without the source selector (e.g. a restored selection) still
// resolves when the caller has no agent of that ID.
func TestResolveAgent_UsesShareWhenNoOwnAgentMatches(t *testing.T) {
c, ctx := newResolveAgentTestContext(7)
sharedAgent := &types.CustomAgent{ID: "3f0c2d9e-shared", TenantID: 84, Name: "Shared"}
h := &Handler{
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
customAgentService: &resolveOwnAgentStub{err: errors.New("agent not found")},
}
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, sharedAgent.ID, 0)
require.Equal(t, sharedAgent, agent)
require.Equal(t, uint64(84), effectiveTenantID)
require.True(t, sharedReadOnly)
}
func TestTerminalProvisionPin_UsesSharedAgentSandboxConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(
http.MethodGet,
"/?agent_id=builtin-smart-reasoning&agent_source_tenant_id=84",
nil,
)
c.Set(types.UserIDContextKey.String(), "user-1")
c.Set(types.TenantIDContextKey.String(), uint64(7))
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7))
c.Request = c.Request.WithContext(ctx)
sharedAgent := &types.CustomAgent{
ID: "builtin-smart-reasoning",
TenantID: 84,
Config: types.CustomAgentConfig{SandboxConfigID: "shared-cfg"},
}
h := &Handler{
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{
ID: "builtin-smart-reasoning",
TenantID: 7,
Config: types.CustomAgentConfig{SandboxConfigID: "local-cfg"},
}},
}
require.Equal(t, service.SandboxPin{}, h.terminalProvisionPin(ctx, c, false),
"lookup-only connects must not resolve an agent config")
// The lending workspace travels with the config id: sandbox configs are
// keyed by (tenant, id), so "shared-cfg" does not exist in workspace 7.
require.Equal(t,
service.SandboxPin{ConfigID: "shared-cfg", TenantID: 84},
h.terminalProvisionPin(ctx, c, true))
}
// An own agent's config already lives in the caller's workspace, so the pin
// carries no owner and SandboxPin.TenantOr falls back to the request tenant.
func TestTerminalProvisionPin_OwnAgentCarriesNoWorkspace(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(
http.MethodGet, "/?agent_id=builtin-smart-reasoning", nil)
c.Set(types.UserIDContextKey.String(), "user-1")
c.Set(types.TenantIDContextKey.String(), uint64(7))
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(7))
c.Request = c.Request.WithContext(ctx)
h := &Handler{
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{
ID: "builtin-smart-reasoning",
TenantID: 7,
Config: types.CustomAgentConfig{SandboxConfigID: "local-cfg"},
}},
}
pin := h.terminalProvisionPin(ctx, c, true)
require.Equal(t, service.SandboxPin{ConfigID: "local-cfg"}, pin)
require.Equal(t, uint64(7), pin.TenantOr(7))
}
+174
View File
@@ -0,0 +1,174 @@
package session
import (
"context"
stderrors "errors"
"strings"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/storageurl"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// resourceModeError turns a mode-resolution failure into the response the client
// should see: a rejected scope is a 403, a typo in the parameter is a 400.
func resourceModeError(err error) error {
if stderrors.Is(err, storageurl.ErrPublicModeForbidden) {
return errors.NewForbiddenError(err.Error())
}
return errors.NewBadRequestError(err.Error())
}
// resolveResourceRewriter builds the storage-reference rewriter for one response
// from the request's `resource_urls` parameter, falling back to the deployment
// default. The returned error is already an AppError the caller can hand to
// c.Error.
//
// In the default handle mode the returned rewriter is disabled, so responses are
// left exactly as before.
func (h *Handler) resolveResourceRewriter(c *gin.Context) (*storageurl.Rewriter, error) {
ctx := c.Request.Context()
mode, err := storageurl.ResolveMode(ctx, c.Query(storageurl.QueryParam))
if err != nil {
return nil, resourceModeError(err)
}
return storageurl.NewRequestRewriter(ctx, mode, h.fileService, h.storageResolver), nil
}
// resolveStreamRewriter is resolveResourceRewriter plus the holdback buffer an
// SSE response needs, because a storage reference can straddle two deltas. It
// must be called before any SSE header is written so an invalid value is still
// reportable as a normal JSON error.
func (h *Handler) resolveStreamRewriter(c *gin.Context) (*storageurl.StreamRewriter, error) {
rewriter, err := h.resolveResourceRewriter(c)
if err != nil {
return nil, err
}
return storageurl.NewStreamRewriter(rewriter), nil
}
// deltaResponseTypes are the SSE events whose Content is an incremental chunk
// that clients accumulate. A storage reference can straddle two chunks, so these
// go through the holdback buffer; every other event carries a complete value.
var deltaResponseTypes = map[types.ResponseType]bool{
types.ResponseTypeAnswer: true,
types.ResponseTypeThinking: true,
types.ResponseTypeReflection: true,
}
// terminalResponseTypes end the message as far as the client is concerned, so
// any buffered tail must be released just before them. An error can be the last
// event a run produces, and a completion may or may not follow it; flushing an
// already-empty buffer is a no-op, so covering both is safe.
var terminalResponseTypes = map[types.ResponseType]bool{
types.ResponseTypeComplete: true,
types.ResponseTypeError: true,
}
// holdbackKey identifies one delta stream. The event id is the key clients
// accumulate on, so interleaved answer and thinking streams hold back
// independently; the type prefix lets a flushed remainder be re-emitted as the
// event type it came from.
func holdbackKey(responseType types.ResponseType, eventID string) string {
return string(responseType) + "\x00" + eventID
}
func parseHoldbackKey(key string) (types.ResponseType, string) {
responseType, eventID, _ := strings.Cut(key, "\x00")
return types.ResponseType(responseType), eventID
}
// buildStreamResponseFor builds the SSE payload for evt and, in public mode,
// replaces storage references with URLs the client can load directly.
func buildStreamResponseFor(
ctx context.Context,
evt interfaces.StreamEvent,
requestID string,
rewriter *storageurl.StreamRewriter,
) *types.StreamResponse {
response := buildStreamResponse(evt, requestID)
if !rewriter.Enabled() {
return response
}
response.KnowledgeReferences = rewriter.Rewriter().CopyReferences(ctx, response.KnowledgeReferences)
response.Data = rewriter.Rewriter().CopyData(ctx, response.Data)
if deltaResponseTypes[evt.Type] {
// The rewritten Data rides along with the held tail so a late release
// carries the same metadata as the event it was cut from.
response.Content = rewriter.Push(
ctx, holdbackKey(evt.Type, evt.ID), response.Content, evt.Done, response.Data)
} else {
response.Content = rewriter.Rewriter().String(ctx, response.Content)
}
return response
}
// emitStreamEvent writes one SSE payload. Content still sitting in the holdback
// buffer is released first when evt terminates the stream, because clients treat
// the completion marker as the end of the message.
func emitStreamEvent(
ctx context.Context,
c *gin.Context,
evt interfaces.StreamEvent,
requestID string,
rewriter *storageurl.StreamRewriter,
) {
response := buildStreamResponseFor(ctx, evt, requestID, rewriter)
if terminalResponseTypes[evt.Type] {
flushHeldStreamContent(ctx, c, requestID, rewriter)
}
c.SSEvent("message", response)
c.Writer.Flush()
}
// flushHeldStreamContent emits whatever the holdback buffer still retains, so a
// trailing reference is not dropped when a delta stream ends without a terminal
// chunk. Every path that stops streaming while the client is still connected
// must call it — completion, a user-requested stop, or giving up on the event
// store — otherwise the tail is silently lost. If the client has already gone
// there is nobody left to receive it.
func flushHeldStreamContent(
ctx context.Context,
c *gin.Context,
requestID string,
rewriter *storageurl.StreamRewriter,
) {
held := rewriter.FlushAll(ctx)
if len(held) == 0 || c.Request.Context().Err() != nil {
return
}
for key, fragment := range held {
if fragment.Content == "" {
continue
}
responseType, eventID := parseHoldbackKey(key)
logger.Debugf(ctx, "Flushing held stream fragment, type: %s, event: %s", responseType, eventID)
c.SSEvent("message", &types.StreamResponse{
ID: requestID,
ResponseType: responseType,
Content: fragment.Content,
Data: heldFragmentData(fragment.Meta, eventID),
})
c.Writer.Flush()
}
}
// heldFragmentData rebuilds the metadata for a released tail from the event it
// was cut from, so a client keying off `event_id` — or off anything else the
// original event carried, such as `is_fallback` — sees the same shape. The map
// is copied because an unchanged rewrite returns the stream buffer's own map.
func heldFragmentData(meta interface{}, eventID string) map[string]interface{} {
original, _ := meta.(map[string]interface{})
data := make(map[string]interface{}, len(original)+1)
for key, value := range original {
data[key] = value
}
if _, ok := data["event_id"]; !ok {
data["event_id"] = eventID
}
return data
}
@@ -0,0 +1,256 @@
package session
import (
"context"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/event"
"academy/internal/storageurl"
"academy/internal/types"
"academy/internal/types/interfaces"
)
const testResourceHandle = "resource://xifDo7NTSL300Lp1goVutw"
// stubResourceFileService resolves any storage reference to one fixed public URL.
type stubResourceFileService struct {
interfaces.FileService
}
func (s *stubResourceFileService) GetFileURL(context.Context, string) (string, error) {
return "https://cdn.example.com/signed.png", nil
}
func (s *stubResourceFileService) SaveFile(
context.Context, *multipart.FileHeader, uint64, string,
) (string, error) {
return "", nil
}
func (s *stubResourceFileService) GetFile(context.Context, string) (io.ReadCloser, error) {
return nil, nil
}
func publicStreamRewriter() *storageurl.StreamRewriter {
return storageurl.NewStreamRewriter(storageurl.NewRequestRewriter(
context.Background(), storageurl.ModePublic, &stubResourceFileService{}, nil))
}
func newTestGinContext(t *testing.T, query string) (*gin.Context, *httptest.ResponseRecorder) {
t.Helper()
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/knowledge-chat/sess1"+query, nil)
return c, recorder
}
// The default mode must leave the stream byte-identical and unbuffered.
func TestResolveStreamRewriter_DefaultIsDisabled(t *testing.T) {
h := &Handler{fileService: &stubResourceFileService{}}
c, _ := newTestGinContext(t, "")
rewriter, err := h.resolveStreamRewriter(c)
require.NoError(t, err)
assert.False(t, rewriter.Enabled())
}
func TestResolveStreamRewriter_RejectsInvalidValue(t *testing.T) {
h := &Handler{fileService: &stubResourceFileService{}}
c, _ := newTestGinContext(t, "?resource_urls=signed")
_, err := h.resolveStreamRewriter(c)
require.Error(t, err)
assert.Contains(t, err.Error(), "resource_urls")
}
// The default mode must not alter a payload at all.
func TestBuildStreamResponseFor_DisabledPassesThrough(t *testing.T) {
rewriter := storageurl.NewStreamRewriter(storageurl.NewRewriter(nil, "TEST"))
evt := interfaces.StreamEvent{
ID: "answer-1",
Type: types.ResponseTypeAnswer,
Content: "see ![fig](" + testResourceHandle + ")",
}
response := buildStreamResponseFor(context.Background(), evt, "req-1", rewriter)
assert.Equal(t, evt.Content, response.Content)
}
// Answer deltas are chunks the client accumulates, so a handle split across two
// events must be held back and rewritten once complete rather than emitted broken.
func TestBuildStreamResponseFor_HoldsReferenceSplitAcrossDeltas(t *testing.T) {
rewriter := publicStreamRewriter()
ctx := context.Background()
first := buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "answer-1",
Type: types.ResponseTypeAnswer,
Content: "see ![fig](resource://xifDo7",
}, "req-1", rewriter)
assert.Equal(t, "see ", first.Content, "the incomplete reference must be held back")
second := buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "answer-1",
Type: types.ResponseTypeAnswer,
Content: "NTSL300Lp1goVutw) done",
}, "req-1", rewriter)
assert.Equal(t, "![fig](https://cdn.example.com/signed.png) done", second.Content)
}
// Interleaved answer and thinking streams must not corrupt each other's buffers.
func TestBuildStreamResponseFor_DeltaStreamsAreIndependent(t *testing.T) {
rewriter := publicStreamRewriter()
ctx := context.Background()
answer := buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "![a](resource://xifDo7NTSL",
}, "req-1", rewriter)
assert.Empty(t, answer.Content)
thinking := buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "think-1", Type: types.ResponseTypeThinking, Content: "reasoning text",
}, "req-1", rewriter)
assert.Equal(t, "reasoning text", thinking.Content)
answer = buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "300Lp1goVutw)",
}, "req-1", rewriter)
assert.Equal(t, "![a](https://cdn.example.com/signed.png)", answer.Content)
}
// Non-delta events carry a complete value, so they must be rewritten immediately
// rather than waiting for a chunk that will never arrive.
func TestBuildStreamResponseFor_NonDeltaContentIsRewrittenImmediately(t *testing.T) {
response := buildStreamResponseFor(context.Background(), interfaces.StreamEvent{
ID: "tool-1",
Type: types.ResponseTypeToolResult,
Content: "chart ![c](" + testResourceHandle + ")",
}, "req-1", publicStreamRewriter())
assert.Equal(t, "chart ![c](https://cdn.example.com/signed.png)", response.Content)
}
// The references payload and tool metadata share pointers and maps with the
// stream replay buffer, so rewriting must not mutate the source event.
func TestBuildStreamResponseFor_DoesNotMutateSourceEvent(t *testing.T) {
reference := &types.SearchResult{Content: "chunk ![c](" + testResourceHandle + ")"}
evt := interfaces.StreamEvent{
ID: "refs-1",
Type: types.ResponseTypeReferences,
Data: map[string]interface{}{
"references": types.References{reference},
"output": "chart ![o](" + testResourceHandle + ")",
},
}
response := buildStreamResponseFor(context.Background(), evt, "req-1", publicStreamRewriter())
require.Len(t, response.KnowledgeReferences, 1)
assert.Equal(t, "chunk ![c](https://cdn.example.com/signed.png)",
response.KnowledgeReferences[0].Content)
assert.Equal(t, "chunk ![c]("+testResourceHandle+")", reference.Content,
"the replay buffer's SearchResult must be untouched")
assert.Equal(t, "chart ![o]("+testResourceHandle+")", evt.Data["output"],
"the replay buffer's metadata map must be untouched")
assert.Equal(t, "chart ![o](https://cdn.example.com/signed.png)", response.Data["output"])
}
// A trailing reference held back when the stream ends must still be delivered,
// as the event type it came from, before the completion marker.
func TestEmitStreamEvent_FlushesHeldContentBeforeCompletion(t *testing.T) {
rewriter := publicStreamRewriter()
ctx := context.Background()
c, recorder := newTestGinContext(t, "?resource_urls=public")
held := buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "tail ![fig](resource://xifDo7",
}, "req-1", rewriter)
require.Equal(t, "tail ", held.Content)
emitStreamEvent(ctx, c, interfaces.StreamEvent{
ID: "complete-1", Type: types.ResponseTypeComplete, Done: true,
}, "req-1", rewriter)
body := recorder.Body.String()
assert.Contains(t, body, `"response_type":"answer"`)
assert.Contains(t, body, `![fig](resource://xifDo7`,
"an incomplete reference cannot be resolved, but must not be swallowed")
assert.Less(t,
indexOf(body, `"response_type":"answer"`),
indexOf(body, `"response_type":"complete"`),
"held content must precede the completion marker",
)
}
// An error can be the last event of a run, so it must release the buffer too —
// otherwise the tail generated before the failure is lost.
func TestEmitStreamEvent_FlushesHeldContentOnError(t *testing.T) {
rewriter := publicStreamRewriter()
ctx := context.Background()
c, recorder := newTestGinContext(t, "?resource_urls=public")
buildStreamResponseFor(ctx, interfaces.StreamEvent{
ID: "answer-1",
Type: types.ResponseTypeAnswer,
Content: "tail ![fig](resource://xifDo7",
Data: map[string]interface{}{"event_id": "answer-1", "is_fallback": true},
}, "req-1", rewriter)
emitStreamEvent(ctx, c, interfaces.StreamEvent{
ID: "err-1", Type: types.ResponseTypeError, Content: "upstream failed", Done: true,
}, "req-1", rewriter)
body := recorder.Body.String()
assert.Contains(t, body, `![fig](resource://xifDo7`, "the tail must not be swallowed")
assert.Contains(t, body, `"is_fallback":true`,
"a released tail must carry the metadata of the event it was cut from")
assert.Less(t,
indexOf(body, `"response_type":"answer"`),
indexOf(body, `"response_type":"error"`),
"held content must precede the error",
)
}
// A user-requested stop ends the stream without a completion event, and the text
// generated before it is still the user's content.
func TestHandleAgentEventsForSSE_FlushesHeldContentOnStop(t *testing.T) {
h := &Handler{streamManager: &stubStreamManager{events: []interfaces.StreamEvent{
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "tail ![fig](resource://xifDo7"},
{ID: "stop-1", Type: types.ResponseType(event.EventStop), Done: true},
}}}
c, recorder := newTestGinContext(t, "?resource_urls=public")
h.handleAgentEventsForSSE(
context.Background(), c, "sess1", "msg1", "req-1", nil, false, publicStreamRewriter())
body := recorder.Body.String()
assert.Contains(t, body, `![fig](resource://xifDo7`, "the tail must not be swallowed")
assert.Less(t,
indexOf(body, `"response_type":"answer"`),
indexOf(body, `"response_type":"stop"`),
"held content must precede the stop notification",
)
}
func TestHoldbackKeyRoundTrip(t *testing.T) {
responseType, eventID := parseHoldbackKey(holdbackKey(types.ResponseTypeThinking, "think-1"))
assert.Equal(t, types.ResponseTypeThinking, responseType)
assert.Equal(t, "think-1", eventID)
}
func indexOf(haystack, needle string) int {
for i := 0; i+len(needle) <= len(haystack); i++ {
if haystack[i:i+len(needle)] == needle {
return i
}
}
return -1
}
+382
View File
@@ -0,0 +1,382 @@
package session
import (
"context"
"encoding/json"
"fmt"
"time"
"academy/internal/agent"
"academy/internal/agent/hitl"
"academy/internal/application/service"
"academy/internal/event"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// SetSuspendedRuns wires what resuming and superseding suspended runs need.
// Without it answers to suspended prompts are recorded but never resumed, and
// new messages leave suspended prompts to expire.
func (h *Handler) SetSuspendedRuns(broker *hitl.Broker, runs *service.SuspendedRunService) {
h.promptBroker, h.suspendedRuns = broker, runs
}
func (h *Handler) supersedeSuspendedRuns(ctx context.Context, sessionID string) {
if h.suspendedRuns == nil {
return
}
if _, err := h.suspendedRuns.SupersedeSession(context.WithoutCancel(ctx), sessionID); err != nil {
logger.Warnf(ctx, "supersede suspended runs of session %s: %v", sessionID, err)
}
}
// How long resuming waits for the run that suspended to finish tearing down,
// and how often it looks. A run suspends its prompt before it has persisted
// the message and released the session, so an answer can arrive first.
var (
resumeSettleTimeout = 15 * time.Second
resumeSettleInterval = 250 * time.Millisecond
)
// ResumeSuspendedRun continues the run suspended on prompt, which c has just
// answered, on this replica. It returns once the run has started; the run
// streams to the message's event stream, where clients attach as they do to
// any live run. ownerGone is hitl.Resolution.OwnerGone.
func (h *Handler) ResumeSuspendedRun(
c *gin.Context, prompt *types.AgentPrompt, ownerGone bool, ownerLeaseUntil *time.Time,
) {
if h.HandlesDelegatedPrompt(c.Request.Context(), prompt) {
return
}
if h.promptBroker == nil || h.suspendedRuns == nil {
return
}
ctx := logger.CloneContext(context.WithoutCancel(c.Request.Context()))
stopLease := h.promptBroker.KeepLease(ctx, prompt.ID, prompt.OwnerInstance)
if err := h.awaitSuspendedRunSettled(ctx, prompt, ownerGone, ownerLeaseUntil); err != nil {
stopLease()
logger.Errorf(ctx, "resume run of prompt %s: %v", prompt.ID, err)
state, _ := h.promptBroker.Suspensions().Get(ctx, prompt.AssistantMessageID)
if state != nil && state.PromptID != prompt.ID {
state = nil
}
h.abandonResume(ctx, prompt, state)
return
}
reqCtx, state, err := h.buildResumeRequest(ctx, c, prompt)
if err != nil {
stopLease()
logger.Errorf(ctx, "resume run of prompt %s: %v", prompt.ID, err)
h.abandonResume(ctx, prompt, state)
return
}
go func() {
defer stopLease()
defer func() {
if r := recover(); r != nil {
logger.Errorf(ctx, "resumed run of prompt %s panicked: %v", prompt.ID, r)
}
h.finishResume(ctx, prompt, state)
}()
h.executeQA(reqCtx, qaModeAgent, false)
}()
}
// awaitSuspendedRunSettled waits until the run that suspended on prompt has
// let go of its message: the message is persisted as awaiting input and the
// session's live-run marker no longer names it. Resuming earlier would race
// that run's teardown, which rewrites the message and clears the marker the
// resumed run sets. A marker left by an owner that is gone is cleared here,
// since nothing else will.
func (h *Handler) awaitSuspendedRunSettled(
ctx context.Context, prompt *types.AgentPrompt, ownerGone bool, ownerLeaseUntil *time.Time,
) error {
deadline := time.Now().Add(resumeSettleTimeout)
if ownerLeaseUntil != nil && ownerLeaseUntil.After(deadline) {
deadline = *ownerLeaseUntil
}
for {
msg, err := h.messageService.GetMessage(ctx, prompt.SessionID, prompt.AssistantMessageID)
if err != nil {
return fmt.Errorf("load assistant message: %w", err)
}
if msg == nil || msg.IsCompleted {
return fmt.Errorf("assistant message is no longer open")
}
if msg.RunState != types.MessageRunStateAwaitingInput &&
(ownerGone || (ownerLeaseUntil != nil && time.Now().After(deadline))) {
// The waiter may have died after suspending the prompt but before
// persisting its message. Rebuild it from the durable snapshot.
if h.promptBroker == nil || h.suspendedRuns == nil {
return fmt.Errorf("suspended run recovery is unavailable")
}
state, err := h.promptBroker.Suspensions().Get(ctx, prompt.AssistantMessageID)
if err != nil {
return fmt.Errorf("read suspended run state: %w", err)
}
if state == nil || state.PromptID != prompt.ID {
return fmt.Errorf("no run state saved for prompt %s", prompt.ID)
}
if err := h.suspendedRuns.MarkAwaitingInput(ctx, prompt, state); err != nil {
return fmt.Errorf("restore suspended message: %w", err)
}
msg.RunState = types.MessageRunStateAwaitingInput
}
if msg.RunState == types.MessageRunStateAwaitingInput {
liveID, _, err := h.streamManager.GetLiveRun(ctx, prompt.SessionID)
if err != nil {
return fmt.Errorf("look up live run: %w", err)
}
if liveID != msg.ID {
return nil
}
if ownerGone || time.Now().After(deadline) {
if err := h.streamManager.ClearLiveRun(ctx, prompt.SessionID, msg.ID); err != nil {
return fmt.Errorf("clear stale live run: %w", err)
}
return nil
}
}
if time.Now().After(deadline) {
return fmt.Errorf("the suspended run did not finish within %s", resumeSettleTimeout)
}
time.Sleep(resumeSettleInterval)
}
}
// buildResumeRequest rebuilds the request of the suspended run from what it
// saved. The returned state is non-nil whenever the run state could be read.
func (h *Handler) buildResumeRequest(
ctx context.Context, c *gin.Context, prompt *types.AgentPrompt,
) (*qaRequestContext, *types.AgentRunSuspension, error) {
state, err := h.promptBroker.Suspensions().Get(ctx, prompt.AssistantMessageID)
if err != nil {
return nil, nil, fmt.Errorf("read run state: %w", err)
}
if state == nil || state.PromptID != prompt.ID {
return nil, nil, fmt.Errorf("no run state saved for this prompt")
}
state.Snapshot, err = h.restoreResumeUserMessages(ctx, prompt.SessionID, state.Snapshot)
if err != nil {
return nil, state, err
}
var req types.ResumableAgentRequest
if err := decodeResumableRequest(state.Snapshot, &req); err != nil {
return nil, state, err
}
if req.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, req.Language)
}
session, err := h.sessionService.GetSession(ctx, prompt.SessionID)
if err != nil || session == nil {
return nil, state, fmt.Errorf("load session: %v", err)
}
if session.Kind == types.SessionKindAgentDelegated {
return nil, state, fmt.Errorf("delegated prompts must resume through the scheduler")
}
msg, err := h.messageService.GetMessage(ctx, prompt.SessionID, prompt.AssistantMessageID)
if err != nil || msg == nil {
return nil, state, fmt.Errorf("load assistant message: %v", err)
}
if msg.IsCompleted || msg.RunState != types.MessageRunStateAwaitingInput {
return nil, state, fmt.Errorf("assistant message is not awaiting input")
}
customAgent, effectiveTenantID, shared := h.resolveAgent(ctx, c, req.AgentID, sharedSourceTenant(session, req))
if customAgent == nil {
return nil, state, fmt.Errorf("agent %s is no longer available", req.AgentID)
}
if types.RunsInSharedKBWorkspace(customAgent) {
// The saved tenant is the KB's execution workspace, not an agent
// share. Resolve the local built-in again and recheck the current
// caller's KB permission before borrowing that workspace's resources.
customAgent, effectiveTenantID = h.resolveWikiFixerTenantScope(
ctx, customAgent, session.TenantID, types.TenantRoleFromContext(ctx), req.KnowledgeBaseIDs,
)
}
if types.IsBuiltinAgentID(req.AgentID) && req.AgentTenantID != 0 &&
req.AgentTenantID != session.TenantID && effectiveTenantID != req.AgentTenantID {
return nil, state, fmt.Errorf("shared KB workspace is no longer available for agent %s", req.AgentID)
}
// Mark the message as generating again before the run publishes itself
// as live: an awaiting message is not treated as a live run.
msg.RunState = ""
msg.UpdatedAt = time.Now()
if err := h.messageService.UpdateMessage(ctx, msg); err != nil {
return nil, state, fmt.Errorf("reopen assistant message: %w", err)
}
if err := h.streamManager.ResetEvents(ctx, prompt.SessionID, msg.ID); err != nil {
logger.Warnf(ctx, "reset events of message %s: %v", msg.ID, err)
}
// Steering messages must stay in the original assistant's history turn.
requestID := msg.RequestID
if requestID == "" {
requestID = prompt.RequestID
}
return &qaRequestContext{
ctx: ctx,
query: req.Query,
userInput: req.Query,
// The run outlives this request, and gin recycles its context.
c: c.Copy(),
sessionID: prompt.SessionID,
requestID: requestID,
receivedAt: time.Now(),
session: session,
customAgent: customAgent,
assistantMessage: msg,
knowledgeBaseIDs: req.KnowledgeBaseIDs,
knowledgeIDs: req.KnowledgeIDs,
tagScopes: req.TagScopes,
mcpServiceIDs: req.MCPServiceIDs,
skillNames: req.SkillNames,
summaryModelID: req.SummaryModelID,
reasoningEffort: req.ReasoningEffort,
webSearchEnabled: req.WebSearchEnabled,
effectiveTenantID: effectiveTenantID,
sharedAgentReadOnly: shared && req.SharedAgentReadOnly,
userMessageID: req.UserMessageID,
channel: msg.Channel,
questionOrigin: req.QuestionOrigin,
pageContext: req.PageContext,
assistantAccess: req.AssistantAccess,
skipSSE: true,
resume: &types.AgentResume{Snapshot: state.Snapshot, Prompt: prompt},
}, state, nil
}
// sharedSourceTenant is the workspace to resolve a shared agent from, or 0
// for the session's own agents.
func sharedSourceTenant(session *types.Session, req types.ResumableAgentRequest) uint64 {
// Built-ins are never shared agents. A different tenant can only be the
// execution scope of a shared KB, which must be revalidated separately.
if types.IsBuiltinAgentID(req.AgentID) || req.AgentTenantID == 0 || req.AgentTenantID == session.TenantID {
return 0
}
return req.AgentTenantID
}
// finishResume closes what the resumed run left open: a prompt it never got
// to act on, and the run state it no longer needs. A run that suspended
// again saved state for its new prompt, which is kept.
func (h *Handler) finishResume(ctx context.Context, prompt *types.AgentPrompt, state *types.AgentRunSuspension) {
row, err := h.promptBroker.Store().Get(ctx, prompt.ID)
if err == nil && row != nil && row.Status == types.AgentPromptAnswered {
// The message now belongs to the prompt the run suspended on again;
// closing it from the old state would complete it under that prompt.
if cur, _ := h.promptBroker.Suspensions().Get(ctx, prompt.AssistantMessageID); cur != nil &&
cur.PromptID != prompt.ID {
h.promptBroker.Fail(ctx, prompt.ID, hitl.ReasonResumeStopped)
return
}
h.abandonResume(ctx, prompt, state)
return
}
if err := h.promptBroker.Suspensions().Delete(ctx, prompt.AssistantMessageID, prompt.ID); err != nil {
logger.Warnf(ctx, "drop run state of message %s: %v", prompt.AssistantMessageID, err)
}
}
// abandonResume fails a prompt whose run could not be resumed and completes
// its message, so it neither waits for the reaper nor stays open.
func (h *Handler) abandonResume(ctx context.Context, prompt *types.AgentPrompt, state *types.AgentRunSuspension) {
h.promptBroker.Fail(ctx, prompt.ID, hitl.ReasonResumeStopped)
if state != nil {
if err := h.suspendedRuns.Close(ctx, prompt, state, hitl.ReasonResumeStopped); err != nil {
logger.Warnf(ctx, "close run of message %s: %v", prompt.AssistantMessageID, err)
}
}
if err := h.promptBroker.Suspensions().Delete(ctx, prompt.AssistantMessageID, prompt.ID); err != nil {
logger.Warnf(ctx, "drop run state of message %s: %v", prompt.AssistantMessageID, err)
}
}
func decodeResumableRequest(snapshot []byte, req *types.ResumableAgentRequest) error {
snap, err := agent.DecodeRunSnapshot(snapshot)
if err != nil {
return err
}
if len(snap.Request) == 0 {
return fmt.Errorf("run state carries no request")
}
if err := json.Unmarshal(snap.Request, req); err != nil {
return fmt.Errorf("decode saved request: %w", err)
}
if req.Query == "" {
// Snapshots written before Query was included in the request.
req.Query = snap.Query
}
return nil
}
// Older snapshots retained steering boundaries but not their text. Resolve
// those IDs from the same session before replaying, including the pending round.
func (h *Handler) restoreResumeUserMessages(
ctx context.Context, sessionID string, snapshot []byte,
) (types.JSON, error) {
snap, err := agent.DecodeRunSnapshot(snapshot)
if err != nil {
return nil, err
}
if snap.UserMessages == nil {
snap.UserMessages = make(map[string]string)
}
steps := append(append([]types.AgentStep(nil), snap.CompletedSteps...), snap.PendingRound.Step)
for _, step := range steps {
for _, id := range step.UserMessagesBefore {
if _, ok := snap.UserMessages[id]; ok {
continue
}
msg, err := h.messageService.GetMessage(ctx, sessionID, id)
if err != nil {
return nil, fmt.Errorf("load steered message %s: %w", id, err)
}
if msg == nil || msg.Role != "user" || msg.SessionID != sessionID {
return nil, fmt.Errorf("steered message %s is not a user message of this session", id)
}
snap.UserMessages[id] = msg.Content
}
}
data, err := json.Marshal(snap)
return types.JSON(data), err
}
func (h *Handler) writeRunResumedEvent(ctx context.Context, sessionID, messageID, promptID string) {
if err := h.streamManager.AppendEvent(ctx, sessionID, messageID, interfaces.StreamEvent{
ID: "resumed-" + promptID,
Type: types.ResponseTypeRunResumed,
Timestamp: time.Now(),
Data: map[string]interface{}{"pending_id": promptID},
}); err != nil {
logger.Warnf(ctx, "append run_resumed of message %s: %v", messageID, err)
}
}
// SetDelegatedPromptRouter installs the delegated prompt ownership router.
func (h *Handler) SetDelegatedPromptRouter(f func(context.Context, *types.AgentPrompt) bool) {
h.delegatedPrompt = f
}
// HandlesDelegatedPrompt reports whether the collaboration runtime owns this prompt.
func (h *Handler) HandlesDelegatedPrompt(ctx context.Context, p *types.AgentPrompt) bool {
return h.delegatedPrompt != nil && h.delegatedPrompt(ctx, p)
}
// CollaborationEvents publishes a child or resumed parent execution to its own stream.
func (h *Handler) CollaborationEvents(ctx context.Context,
s *types.Session,
m *types.Message,
bus *event.EventBus,
) func(context.Context) error {
stream := h.setupStreamHandler(ctx, s.ID, m.ID, m.RequestID, s.TenantID, time.Now(), m, bus)
return stream.publishCompletion
}
// CollaborationSteer builds a steer sink for a collaboration execution.
func (h *Handler) CollaborationSteer(ctx context.Context, s *types.Session, m *types.Message) types.SteerSink {
return newSteerSink(ctx, s.ID, m.RequestID, m, h.messageService, h.streamManager)
}
@@ -0,0 +1,203 @@
package session
import (
"context"
"encoding/json"
"path/filepath"
"testing"
"time"
"academy/internal/agent"
"academy/internal/agent/hitl"
"academy/internal/application/service"
"academy/internal/stream"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type resumeMessages struct {
interfaces.MessageService
rows map[string]*types.Message
}
type resumeKBService struct {
interfaces.KnowledgeBaseService
*wikiFixerKBLookupStub
}
func (s *resumeKBService) GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error) {
return s.wikiFixerKBLookupStub.GetKnowledgeBaseByIDOnly(ctx, id)
}
type resumeKBShareService struct {
interfaces.KBShareService
*wikiFixerKBShareStub
}
func (s *resumeKBShareService) CheckTenantKBPermission(
ctx context.Context, kbID string, tenantID uint64, role types.TenantRole,
) (types.OrgMemberRole, bool, error) {
return s.wikiFixerKBShareStub.CheckTenantKBPermission(ctx, kbID, tenantID, role)
}
func TestBuildResumeRequestRevalidatesSharedKBBuiltin(t *testing.T) {
require.NoError(t, types.LoadBuiltinAgentsConfig(filepath.Join("..", "..", "..", "config")))
for _, agentID := range []string{types.BuiltinAcademyAssistantID, types.BuiltinWikiFixerID} {
for _, allowed := range []bool{true, false} {
name := agentID + "/editor"
if !allowed {
name = agentID + "/revoked"
}
t.Run(name, func(t *testing.T) {
c, ctx := newResolveAgentTestContext(1)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor)
messages := &resumeMessages{rows: map[string]*types.Message{
"m": {ID: "m", SessionID: "s", RunState: types.MessageRunStateAwaitingInput},
}}
b := hitl.NewBroker(nil, nil)
request, err := json.Marshal(types.ResumableAgentRequest{
AgentID: agentID, AgentTenantID: 2, KnowledgeBaseIDs: []string{"shared-kb"},
PageContext: &types.PageContext{KnowledgeBaseID: "shared-kb"},
})
require.NoError(t, err)
snapshot, err := json.Marshal(agent.RunSnapshot{Version: agent.RunSnapshotVersion, Request: request})
require.NoError(t, err)
require.NoError(t, b.Suspensions().Save(ctx, &types.AgentRunSuspension{
AssistantMessageID: "m", PromptID: "p", Snapshot: types.JSON(snapshot),
}))
permission := types.OrgRoleViewer
if allowed {
permission = types.OrgRoleEditor
}
share := &wikiFixerKBShareStub{permission: permission, isShared: true}
own := types.GetBuiltinAgent(agentID, 1)
h := &Handler{
promptBroker: b, messageService: messages, sessionService: &resumeSessionService{},
streamManager: stream.NewMemoryStreamManager(),
customAgentService: &resolveOwnAgentStub{agent: own},
agentShareService: &resolveAgentShareStub{err: service.ErrAgentShareNotFound},
knowledgebaseService: &resumeKBService{wikiFixerKBLookupStub: &wikiFixerKBLookupStub{
kb: &types.KnowledgeBase{ID: "shared-kb", TenantID: 2},
}},
kbShareService: &resumeKBShareService{wikiFixerKBShareStub: share},
}
req, _, err := h.buildResumeRequest(ctx, c, &types.AgentPrompt{
ID: "p", SessionID: "s", AssistantMessageID: "m", Kind: types.AgentPromptKindToolApproval,
})
if !allowed {
require.Error(t, err)
require.Nil(t, req)
require.Equal(t, types.MessageRunStateAwaitingInput, messages.rows["m"].RunState)
} else {
require.NoError(t, err)
require.Equal(t, uint64(2), req.effectiveTenantID)
require.Equal(t, uint64(2), req.customAgent.TenantID)
require.Equal(t, []string{"shared-kb"}, req.customAgent.Config.KnowledgeBases)
require.False(t, req.sharedAgentReadOnly)
require.Equal(t, "shared-kb", req.buildQARequest().PageContext.KnowledgeBaseID)
}
require.Equal(t, "shared-kb", share.checkedKBID)
require.Equal(t, uint64(1), share.checkedTenantID)
require.Equal(t, uint64(1), own.TenantID)
})
}
}
}
func (m *resumeMessages) GetMessage(_ context.Context, sessionID, id string) (*types.Message, error) {
row := m.rows[id]
if row == nil || row.SessionID != sessionID {
return nil, nil
}
cloned := *row
return &cloned, nil
}
func (m *resumeMessages) UpdateMessage(_ context.Context, row *types.Message) error {
cloned := *row
m.rows[row.ID] = &cloned
return nil
}
type resumeMessageRepo struct {
interfaces.MessageRepository
messages *resumeMessages
}
type resumeSessionService struct{ interfaces.SessionService }
func (*resumeSessionService) GetSession(_ context.Context, id string) (*types.Session, error) {
return &types.Session{ID: id, TenantID: 1}, nil
}
func (r *resumeMessageRepo) GetMessage(ctx context.Context, sessionID, id string) (*types.Message, error) {
return r.messages.GetMessage(ctx, sessionID, id)
}
func (r *resumeMessageRepo) UpdateMessage(ctx context.Context, m *types.Message) error {
return r.messages.UpdateMessage(ctx, m)
}
func TestBuildResumeRequestKeepsTurnAndRestoresLegacySteering(t *testing.T) {
c, ctx := newResolveAgentTestContext(1)
messages := &resumeMessages{rows: map[string]*types.Message{
"m": {ID: "m", SessionID: "sess-1", RequestID: "original-turn", RunState: types.MessageRunStateAwaitingInput},
"u": {ID: "u", SessionID: "sess-1", Role: "user", Content: "use staging"},
}}
b := hitl.NewBroker(nil, nil)
request, err := json.Marshal(types.ResumableAgentRequest{AgentID: "a", UserMessageID: "first"})
require.NoError(t, err)
snapshot, err := json.Marshal(agent.RunSnapshot{
Version: agent.RunSnapshotVersion, Query: "original question", Request: request,
PendingRound: agent.PendingRound{Step: types.AgentStep{UserMessagesBefore: []string{"u"}}},
})
require.NoError(t, err)
require.NoError(t, b.Suspensions().Save(ctx, &types.AgentRunSuspension{
AssistantMessageID: "m", PromptID: "p", Snapshot: types.JSON(snapshot),
}))
h := &Handler{
promptBroker: b, messageService: messages, streamManager: stream.NewMemoryStreamManager(),
sessionService: &resumeSessionService{},
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{ID: "a"}},
}
req, _, err := h.buildResumeRequest(ctx, c, &types.AgentPrompt{
ID: "p", SessionID: "sess-1", AssistantMessageID: "m", RequestID: "transport",
})
require.NoError(t, err)
require.Equal(t, "original question", req.query)
require.Equal(t, req.query, req.userInput)
require.Equal(t, "original-turn", req.requestID)
require.Equal(t, "original question", req.buildQARequest().Query)
snap, err := agent.DecodeRunSnapshot(req.resume.Snapshot)
require.NoError(t, err)
require.Equal(t, "use staging", snap.UserMessages["u"])
}
func TestResumeRecoversOwnerThatDiedBeforeSavingMessage(t *testing.T) {
for _, ownerGone := range []bool{true, false} {
t.Run(map[bool]string{true: "reaped", false: "self-suspended"}[ownerGone], func(t *testing.T) {
shortResumeSettle(t, 20*time.Millisecond)
ctx := t.Context()
messages := &resumeMessages{rows: map[string]*types.Message{"m": {ID: "m", SessionID: "s"}}}
b := hitl.NewBroker(nil, nil)
require.NoError(t, b.Suspensions().Save(ctx, &types.AgentRunSuspension{
AssistantMessageID: "m", PromptID: "p1",
Snapshot: types.JSON(`{"version":1,"completed_steps":[{"thought":"saved work"}]}`),
}))
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(ctx, "s", "m", "old"))
h := &Handler{
messageService: messages, promptBroker: b, streamManager: mgr,
suspendedRuns: service.NewSuspendedRunService(b, &resumeMessageRepo{messages: messages}),
}
past := time.Now().Add(-time.Second)
require.NoError(t, h.awaitSuspendedRunSettled(ctx, settlePrompt, ownerGone, &past))
require.Equal(t, types.MessageRunStateAwaitingInput, messages.rows["m"].RunState)
require.Equal(t, "saved work", messages.rows["m"].AgentSteps[0].Thought)
live, _, err := mgr.GetLiveRun(ctx, "s")
require.NoError(t, err)
require.Empty(t, live)
})
}
}
@@ -0,0 +1,86 @@
package session
import (
"context"
"sync"
"testing"
"time"
"academy/internal/stream"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
)
type settleMessages struct {
interfaces.MessageService
mu sync.Mutex
msg types.Message
}
func (s *settleMessages) GetMessage(context.Context, string, string) (*types.Message, error) {
s.mu.Lock()
defer s.mu.Unlock()
m := s.msg
return &m, nil
}
func (s *settleMessages) set(f func(*types.Message)) {
s.mu.Lock()
defer s.mu.Unlock()
f(&s.msg)
}
func shortResumeSettle(t *testing.T, timeout time.Duration) {
prevTimeout, prevInterval := resumeSettleTimeout, resumeSettleInterval
resumeSettleTimeout, resumeSettleInterval = timeout, 10*time.Millisecond
t.Cleanup(func() { resumeSettleTimeout, resumeSettleInterval = prevTimeout, prevInterval })
}
var settlePrompt = &types.AgentPrompt{ID: "p1", SessionID: "s", AssistantMessageID: "m"}
// An answer that lands while the suspending run is still tearing down waits
// for it to persist the message and release the session.
func TestResumeWaitsForSuspendingRunToFinish(t *testing.T) {
shortResumeSettle(t, 5*time.Second)
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(t.Context(), "s", "m", "req"))
messages := &settleMessages{msg: types.Message{ID: "m", SessionID: "s"}}
h := &Handler{messageService: messages, streamManager: mgr}
go func() {
time.Sleep(50 * time.Millisecond)
messages.set(func(m *types.Message) { m.RunState = types.MessageRunStateAwaitingInput })
time.Sleep(50 * time.Millisecond)
_ = mgr.ClearLiveRun(context.Background(), "s", "m")
}()
start := time.Now()
require.NoError(t, h.awaitSuspendedRunSettled(t.Context(), settlePrompt, false, nil))
require.GreaterOrEqual(t, time.Since(start), 100*time.Millisecond)
}
func TestResumeClearsMarkerLeftByVanishedOwner(t *testing.T) {
shortResumeSettle(t, 5*time.Second)
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(t.Context(), "s", "m", "req"))
messages := &settleMessages{msg: types.Message{
ID: "m", SessionID: "s", RunState: types.MessageRunStateAwaitingInput,
}}
h := &Handler{messageService: messages, streamManager: mgr}
require.NoError(t, h.awaitSuspendedRunSettled(t.Context(), settlePrompt, true, nil))
live, _, err := mgr.GetLiveRun(t.Context(), "s")
require.NoError(t, err)
require.Empty(t, live)
}
func TestResumeGivesUpOnMessageThatNeverSettles(t *testing.T) {
shortResumeSettle(t, 60*time.Millisecond)
messages := &settleMessages{msg: types.Message{ID: "m", SessionID: "s"}}
h := &Handler{messageService: messages, streamManager: stream.NewMemoryStreamManager()}
require.Error(t, h.awaitSuspendedRunSettled(t.Context(), settlePrompt, false, nil))
messages.set(func(m *types.Message) { m.IsCompleted = true })
require.Error(t, h.awaitSuspendedRunSettled(t.Context(), settlePrompt, true, nil))
}
+127
View File
@@ -0,0 +1,127 @@
package session
import (
"context"
stderrors "errors"
"net/http"
"strings"
"academy/internal/application/service"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
// sessionRewinder is the rewind surface the handler needs. Declaring it here
// rather than depending on *service.SessionRewindService keeps the handler
// testable with a stub.
type sessionRewinder interface {
Rewind(
ctx context.Context,
tenantID uint64,
userID, sessionID, messageID string,
) (*service.RewindResult, error)
}
// RewindSessionRequest is the rewind endpoint's body.
type RewindSessionRequest struct {
// MessageID is the message to rewind to. A user message deletes itself and
// everything after (the client prefills that question). An assistant
// message keeps itself and deletes everything after.
MessageID string `json:"message_id" binding:"required"`
}
// RewindSession godoc
// @Summary 回滚会话
// @Description 回滚当前会话到指定用户或助手消息:删除其后消息,可到达时 git reset 工作区。
// @Tags 会话
// @Accept json
// @Produce json
// @Param session_id path string true "会话 ID"
// @Param request body RewindSessionRequest true "回滚请求"
// @Success 200 {object} map[string]interface{} "回滚结果"
// @Failure 400 {object} errors.AppError "请求参数错误 / 回滚点角色不支持"
// @Failure 404 {object} errors.AppError "会话或消息不存在"
// @Failure 409 {object} errors.AppError "会话正在生成中 / 无检查点 / 沙箱已更换"
// @Failure 500 {object} errors.AppError "工作区回滚失败"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/rewind [post]
func (h *Handler) RewindSession(c *gin.Context) {
ctx := c.Request.Context()
sessionID := strings.TrimSpace(c.Param("session_id"))
if sessionID == "" {
sessionID = strings.TrimSpace(c.Param("id"))
}
if sessionID == "" {
_ = c.Error(errors.NewBadRequestError("session ID is required"))
return
}
var req RewindSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("message_id is required"))
return
}
if strings.TrimSpace(req.MessageID) == "" {
_ = c.Error(errors.NewBadRequestError("message_id is required"))
return
}
if h.rewindService == nil {
_ = c.Error(errors.NewServiceUnavailableError("session rewind is not available"))
return
}
tenantID, _ := types.TenantIDFromContext(ctx)
userID := types.SessionOwnerIDFromContext(ctx)
result, err := h.rewindService.Rewind(
ctx, tenantID, userID, sessionID, strings.TrimSpace(req.MessageID),
)
if err != nil {
if stderrors.Is(err, service.ErrRewindSourceBusy) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": "session has an active turn",
"code": "REWIND_SOURCE_BUSY",
})
return
}
if stderrors.Is(err, service.ErrRewindNoCheckpoint) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": "no reachable workspace checkpoint",
"code": "REWIND_NO_CHECKPOINT",
})
return
}
if stderrors.Is(err, service.ErrRewindSandboxReplaced) {
c.JSON(http.StatusConflict, gin.H{
"success": false,
"error": "sandbox was replaced",
"code": "REWIND_SANDBOX_REPLACED",
})
return
}
if stderrors.Is(err, service.ErrRewindSessionNotFound) {
_ = c.Error(errors.NewNotFoundError("session not found"))
return
}
if stderrors.Is(err, service.ErrRewindMessageNotFound) {
_ = c.Error(errors.NewNotFoundError("message not found"))
return
}
if stderrors.Is(err, service.ErrRewindMessageRole) {
_ = c.Error(errors.NewBadRequestError("rewind point must be a user or assistant message"))
return
}
logger.Errorf(ctx, "rewind session %s failed: %v", sessionID, err)
_ = c.Error(errors.NewInternalServerError("rewind session failed"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
+137
View File
@@ -0,0 +1,137 @@
package session
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/service"
"academy/internal/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type stubRewinder struct {
result *service.RewindResult
err error
gotMsg string
}
func (s *stubRewinder) Rewind(
_ context.Context, _ uint64, _, _, messageID string,
) (*service.RewindResult, error) {
s.gotMsg = messageID
return s.result, s.err
}
func performRewind(t *testing.T, rewinder sessionRewinder, body string) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
h := &Handler{rewindService: rewinder}
w := httptest.NewRecorder()
r := gin.New()
r.Use(middleware.ErrorHandler())
r.POST("/sessions/:session_id/rewind", h.RewindSession)
req := httptest.NewRequest(http.MethodPost, "/sessions/src/rewind", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
return w
}
func TestRewindSessionReturnsCounts(t *testing.T) {
rewinder := &stubRewinder{result: &service.RewindResult{
DeletedMessages: 4, WorkspaceReset: true,
}}
w := performRewind(t, rewinder, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "u-2", rewinder.gotMsg)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
data := body["data"].(map[string]any)
require.Equal(t, float64(4), data["deleted_messages"])
require.Equal(t, true, data["workspace_reset"])
require.Equal(t, "", data["reason"])
}
func TestRewindSessionSurfacesSkipReason(t *testing.T) {
rewinder := &stubRewinder{result: &service.RewindResult{
DeletedMessages: 2, WorkspaceReset: false, Reason: service.RewindSkipNoCheckpoint,
}}
w := performRewind(t, rewinder, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusOK, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
data := body["data"].(map[string]any)
require.Equal(t, false, data["workspace_reset"])
require.Equal(t, "NO_CHECKPOINT", data["reason"])
}
func TestRewindSessionRejectsMissingMessageID(t *testing.T) {
rewinder := &stubRewinder{result: &service.RewindResult{DeletedMessages: 1}}
w := performRewind(t, rewinder, `{}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestRewindSessionMapsUnsupportedRoleTo400(t *testing.T) {
rewinder := &stubRewinder{err: service.ErrRewindMessageRole}
w := performRewind(t, rewinder, `{"message_id":"sys-1"}`)
require.Equal(t, http.StatusBadRequest, w.Code)
}
func TestRewindSessionMapsMissingSessionTo404(t *testing.T) {
rewinder := &stubRewinder{err: service.ErrRewindSessionNotFound}
w := performRewind(t, rewinder, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestRewindSessionMapsBusySourceTo409(t *testing.T) {
rewinder := &stubRewinder{err: service.ErrRewindSourceBusy}
w := performRewind(t, rewinder, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusConflict, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, "REWIND_SOURCE_BUSY", body["code"])
}
func TestRewindSessionMapsReplacedSandboxTo409(t *testing.T) {
rewinder := &stubRewinder{err: service.ErrRewindSandboxReplaced}
w := performRewind(t, rewinder, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusConflict, w.Code)
var body map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, "REWIND_SANDBOX_REPLACED", body["code"])
}
func TestRewindSessionUnavailableWhenUnwired(t *testing.T) {
w := performRewind(t, nil, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusServiceUnavailable, w.Code)
}
func TestRewindSessionMapsResetFailureTo500(t *testing.T) {
rewinder := &stubRewinder{err: errors.New("workspace reset: git reset exec: sandbox unreachable")}
w := performRewind(t, rewinder, `{"message_id":"u-2"}`)
require.Equal(t, http.StatusInternalServerError, w.Code)
}
@@ -0,0 +1,353 @@
// Package session provides RFB (VNC) client-stream parsing for the sandbox desktop relay.
//
// The relay is transparent — it forwards bytes without rewriting them — but it
// still has to know where client messages start and end, because idle
// detection is by message opcode, not by byte count. Byte counting was
// rejected: the XFCE panel clock, websockify's --heartbeat 30, and
// ContinuousUpdates all keep bytes flowing forever, so a sandbox would never
// be judged idle and its TTL would be refreshed indefinitely.
//
// Everything here is a pure function or a small state machine with no I/O, so
// the parts that are expensive to debug in production are cheap to test.
package session
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"sync/atomic"
)
// rfbClientHandshakeBytes is how many bytes the CLIENT sends before the
// message stream begins, under RFB 3.8 with security type None:
//
// ProtocolVersion 12 ("RFB 003.008\n")
// security-type 1 (1 = None)
// ClientInit 1 (shared-flag)
//
// RFB 3.3 would be 13 (the server picks the security type), which is why the
// version assertion below is fail-closed rather than informational.
const rfbClientHandshakeBytes = 14
// rfbProtocolVersion38 is the only server version this relay accepts.
var rfbProtocolVersion38 = []byte("RFB 003.008\n")
// rfbSecurityTypeNone is the only security type x11vnc should offer: it runs
// with -nopw, and authentication lives one hop out, on websockify.
const rfbSecurityTypeNone byte = 1
// rfbMaxClientMessageBytes bounds one buffered client message. The largest
// legitimate one is a paste (ClientCutText); 1 MiB is far beyond any real
// clipboard and keeps a malformed length header from pinning memory.
const rfbMaxClientMessageBytes = 1 << 20
// rfbProtocolVersionBytes is the length of the server's opening message, and
// the most the relay can read before the upgrade: under RFB 3.8 the server
// sends these 12 bytes and then waits for the CLIENT's version before it
// offers anything else (RFC 6143 §7.1.1). The relay must not answer — that
// handshake belongs to noVNC — so reading further here only blocks.
const rfbProtocolVersionBytes = 12
// rfbValidateServerVersion is the assertion that still runs before the
// browser socket is upgraded, so a mismatch is an HTTP status code rather
// than a close frame.
func rfbValidateServerVersion(version []byte) error {
if !bytes.Equal(version, rfbProtocolVersion38) {
return fmt.Errorf(
"rfb: server speaks %q, want %q; the client handshake byte count "+
"depends on this", version, rfbProtocolVersion38)
}
return nil
}
// rfbValidateSecurityTypes keeps the "x11vnc offered None and only None"
// guarantee. It can no longer run pre-upgrade (see rfbProtocolVersionBytes),
// so the relay applies it to the first server message instead.
func rfbValidateSecurityTypes(securityTypes []byte) error {
if len(securityTypes) != 1 || securityTypes[0] != rfbSecurityTypeNone {
return fmt.Errorf(
"rfb: server offered security types %v, want exactly [%d] (None); "+
"anything else means start-desktop.sh did not run as expected",
securityTypes, rfbSecurityTypeNone)
}
return nil
}
// rfbValidateServerHandshake enforces both fail-closed assertions at once,
// for callers that already hold the whole handshake.
func rfbValidateServerHandshake(version []byte, securityTypes []byte) error {
if err := rfbValidateServerVersion(version); err != nil {
return err
}
return rfbValidateSecurityTypes(securityTypes)
}
// rfbServerStream applies the security-type assertion to the sandbox→browser
// direction, which is the only place left to make it once the relay stopped
// trying to impersonate the client.
//
// The zero value expects the byte right after the server's ProtocolVersion.
// It inspects exactly one message and then gets out of the way.
type rfbServerStream struct {
buf []byte
done bool
}
// Observe feeds server bytes and reports the first (and only) violation.
func (s *rfbServerStream) Observe(chunk []byte) error {
if s.done || len(chunk) == 0 {
return nil
}
s.buf = append(s.buf, chunk...)
// number-of-security-types, then that many single-byte types.
count := int(s.buf[0])
if count == 0 {
// Zero is RFB's "connection failed" form, carrying a reason string
// rather than an offer. Either way there is no usable desktop here.
s.done = true
s.buf = nil
return errors.New("rfb: server offered no security types")
}
if len(s.buf) < 1+count {
return nil
}
types := append([]byte(nil), s.buf[1:1+count]...)
s.done = true
s.buf = nil
return rfbValidateSecurityTypes(types)
}
// rfbClientMessageSize reports the total byte length of the client message at
// the head of buf.
//
// known - false for an opcode this relay does not model. The caller MUST
// NOT guess a length; see rfbClientStream.Consume.
// complete - true when buf already holds the whole message.
// size - meaningful only when complete is true.
//
// Message layouts are RFC 6143 §7.5 plus the two pseudo-messages libvncserver
// advertises and noVNC therefore sends (150 EnableContinuousUpdates, 248
// ClientFence).
func rfbClientMessageSize(buf []byte) (size int, complete bool, known bool) {
if len(buf) == 0 {
return 0, false, true
}
switch buf[0] {
case 0: // SetPixelFormat
return fixedSize(buf, 20)
case 2: // SetEncodings: 4-byte header + 4 bytes per encoding
if len(buf) < 4 {
return 0, false, true
}
n := int(binary.BigEndian.Uint16(buf[2:4]))
return fixedSize(buf, 4+4*n)
case 3: // FramebufferUpdateRequest
return fixedSize(buf, 10)
case 4: // KeyEvent
return fixedSize(buf, 8)
case 5: // PointerEvent
return fixedSize(buf, 6)
case 6: // ClientCutText: 8-byte header + payload
if len(buf) < 8 {
return 0, false, true
}
return fixedSize(buf, 8+rfbClientCutTextPayload(buf[4:8]))
case 150: // EnableContinuousUpdates
return fixedSize(buf, 10)
case 248: // ClientFence: 9-byte header + payload
if len(buf) < 9 {
return 0, false, true
}
return fixedSize(buf, 9+int(buf[8]))
case 251: // SetDesktopSize: 8-byte header + 16 bytes per screen
// Modelled for completeness, but it should never arrive: the
// frontend pins resizeSession:false in SandboxDesktop.vue. That is a
// parser contract, not a UX preference — do not turn it on without
// re-reading this case.
if len(buf) < 8 {
return 0, false, true
}
return fixedSize(buf, 8+16*int(buf[6]))
default:
return 0, false, false
}
}
// rfbClientCutTextPayload is the payload byte count of a ClientCutText
// message. RFC 6143 uses an unsigned length. The Extended Clipboard
// pseudo-encoding reuses the same opcode with a signed length: negative
// means abs(n) payload bytes. noVNC writes toUnsigned32bit(-data.length);
// reading that as unsigned on amd64 is ~4e9 and Disable()'s idle detection.
func rfbClientCutTextPayload(lengthField []byte) int {
n := int32(binary.BigEndian.Uint32(lengthField))
if n >= 0 {
return int(n)
}
if n == math.MinInt32 {
// -MinInt32 does not fit in int32; not a real clipboard.
return rfbMaxClientMessageBytes
}
return int(-n)
}
func fixedSize(buf []byte, want int) (int, bool, bool) {
if want < 0 || want > rfbMaxClientMessageBytes {
// An implausible declared length: treat it like an unknown opcode
// rather than buffering toward it.
return 0, false, false
}
if len(buf) < want {
return want, false, true
}
return want, true, true
}
// rfbOpcodeCountsAsActivity reports whether a client message means a human
// touched the desktop.
//
// FramebufferUpdateRequest (3) is deliberately excluded: noVNC emits it in
// response to the server's own updates, so a static desktop with a running
// clock produces a steady stream of them.
func rfbOpcodeCountsAsActivity(opcode byte) bool {
switch opcode {
case 4, 5, 6: // KeyEvent, PointerEvent, ClientCutText
return true
default:
return false
}
}
// rfbClientStream tracks one browser→sandbox direction: it skips the 14-byte
// handshake, then splits the message stream and reports user activity.
//
// The zero value is ready to use. It is NOT safe for concurrent use; the relay
// feeds it from a single read goroutine.
type rfbClientStream struct {
handshakeSeen int
buf []byte
disabled atomic.Bool
}
// ParsingEnabled reports whether opcode-based activity detection is still
// live. Once it goes false the connection's idle judgement falls back to the
// frontend's activity POST for good. Safe to call from the activity POST
// while Consume runs on the relay goroutine.
func (s *rfbClientStream) ParsingEnabled() bool { return !s.disabled.Load() }
// Disable stops parsing. Exported to the package so the relay can also switch
// to the fallback for reasons outside this file.
func (s *rfbClientStream) Disable() {
s.disabled.Store(true)
s.buf = nil
}
// Consume feeds one chunk of client bytes and reports whether it contained at
// least one activity message.
//
// Chunk boundaries carry no meaning: a WebSocket frame may hold several
// messages, and one message may span frames. Both cases are covered by tests.
func (s *rfbClientStream) Consume(chunk []byte) bool {
if s.disabled.Load() || len(chunk) == 0 {
return false
}
// Skip whatever remains of the handshake.
if s.handshakeSeen < rfbClientHandshakeBytes {
need := rfbClientHandshakeBytes - s.handshakeSeen
if len(chunk) <= need {
s.handshakeSeen += len(chunk)
return false
}
s.handshakeSeen = rfbClientHandshakeBytes
chunk = chunk[need:]
}
s.buf = append(s.buf, chunk...)
activity := false
for len(s.buf) > 0 {
size, complete, known := rfbClientMessageSize(s.buf)
if !known {
// Never guess a length: one wrong split loses framing for the
// life of the connection.
s.Disable()
return false
}
if !complete {
break
}
if rfbOpcodeCountsAsActivity(s.buf[0]) {
activity = true
}
s.buf = s.buf[size:]
}
// Keep the tail bounded even while waiting for the rest of a message.
if len(s.buf) > rfbMaxClientMessageBytes {
s.Disable()
return false
}
return activity
}
var errRFBHandshakeIncomplete = errors.New("rfb: server handshake ended early")
// rfbReadServerVersion drains the server's 12-byte ProtocolVersion from the
// sandbox connection, asserts it, and returns everything it read so the
// caller can replay it to the browser.
//
// It deliberately stops there. Waiting for the security-type list as well
// deadlocks: the server does not send it until the client answers with its
// own version, and the client here is noVNC, which has not been connected
// yet. That bug looked exactly like a dead upstream — the dial 101'd and the
// read then timed out — while the sandbox was serving other clients fine.
func rfbReadServerVersion(next func() ([]byte, error)) ([]byte, error) {
var buf []byte
for attempt := 0; attempt < 64; attempt++ {
if len(buf) >= rfbProtocolVersionBytes {
if err := rfbValidateServerVersion(buf[:rfbProtocolVersionBytes]); err != nil {
return nil, err
}
return buf, nil
}
chunk, err := next()
if err != nil {
return nil, err
}
buf = append(buf, chunk...)
}
return nil, errRFBHandshakeIncomplete
}
// rfbReadServerHandshake drains the server's opening bytes from the sandbox
// connection, runs the two fail-closed assertions, and returns everything it
// read so the caller can replay it to the browser.
//
// It runs BEFORE the browser socket is upgraded. That ordering is the whole
// reason the assertions can be answered with an HTTP status code instead of a
// close frame the browser shows as a generic disconnect.
//
// next returns the payload of one binary frame from the sandbox, or an error.
func rfbReadServerHandshake(next func() ([]byte, error)) ([]byte, error) {
var buf []byte
// Bound the read: a peer that never completes the handshake must not keep
// us here. 64 frames is far more than the two or three this ever takes.
for attempt := 0; attempt < 64; attempt++ {
// ProtocolVersion(12) + number-of-security-types(1) is the minimum
// before the type list length is even knowable.
if len(buf) >= 13 {
need := 13 + int(buf[12])
if len(buf) >= need {
if err := rfbValidateServerHandshake(buf[:12], buf[13:need]); err != nil {
return nil, err
}
return buf, nil
}
}
chunk, err := next()
if err != nil {
return nil, err
}
buf = append(buf, chunk...)
}
return nil, errRFBHandshakeIncomplete
}
@@ -0,0 +1,293 @@
package session
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestRFBValidateServerHandshake(t *testing.T) {
t.Run("accepts 3.8 with None only", func(t *testing.T) {
require.NoError(t, rfbValidateServerHandshake([]byte("RFB 003.008\n"), []byte{1}))
})
t.Run("rejects 3.3", func(t *testing.T) {
// 3.3 puts 13 bytes on the client side, not 14. Miscounting by one
// loses framing permanently.
err := rfbValidateServerHandshake([]byte("RFB 003.003\n"), []byte{1})
require.Error(t, err)
})
t.Run("rejects extra security types", func(t *testing.T) {
// x11vnc runs with -nopw, so None must be the only offer. Anything
// else means the start script did not run as expected, and relaying
// on would hand the authentication semantics to an unknown path.
err := rfbValidateServerHandshake([]byte("RFB 003.008\n"), []byte{1, 2})
require.Error(t, err)
})
t.Run("rejects VNC-Auth only", func(t *testing.T) {
require.Error(t, rfbValidateServerHandshake([]byte("RFB 003.008\n"), []byte{2}))
})
t.Run("rejects empty security list", func(t *testing.T) {
require.Error(t, rfbValidateServerHandshake([]byte("RFB 003.008\n"), nil))
})
}
func TestRFBReadServerVersionStopsAtTwelveBytes(t *testing.T) {
// RFB 3.8 §7.1.1: the server sends its 12-byte ProtocolVersion and then
// waits for the CLIENT's version before offering security types. The
// relay never answers — noVNC does — so a reader that waits for 13 bytes
// hangs until its deadline. Verified against the live sandbox: silent
// client, zero further bytes in 10s; after replying, types arrive in
// 0.25s.
reads := 0
prelude, err := rfbReadServerVersion(func() ([]byte, error) {
reads++
if reads > 1 {
return nil, errRFBHandshakeIncomplete
}
return []byte("RFB 003.008\n"), nil
})
require.NoError(t, err)
require.Equal(t, []byte("RFB 003.008\n"), prelude)
require.Equal(t, 1, reads, "a second read would block until the deadline")
}
func TestRFBReadServerVersionRejectsWrongVersion(t *testing.T) {
_, err := rfbReadServerVersion(func() ([]byte, error) {
return []byte("RFB 003.003\n"), nil
})
require.Error(t, err)
}
func TestRFBReadServerVersionKeepsCoalescedBytes(t *testing.T) {
// Nothing stops a server from coalescing; whatever arrived must reach
// the browser.
one := append([]byte("RFB 003.008\n"), 1, 1)
prelude, err := rfbReadServerVersion(func() ([]byte, error) { return one, nil })
require.NoError(t, err)
require.Equal(t, one, prelude)
}
func TestRFBServerStreamValidatesSecurityTypes(t *testing.T) {
// The "exactly [None]" assertion cannot run before the upgrade any more,
// so the relay checks it on the first server message instead.
t.Run("accepts None only", func(t *testing.T) {
var s rfbServerStream
require.NoError(t, s.Observe([]byte{1, 1}))
// Later traffic is no longer inspected.
require.NoError(t, s.Observe([]byte{0, 0, 0, 0}))
})
t.Run("accepts a split list", func(t *testing.T) {
var s rfbServerStream
require.NoError(t, s.Observe([]byte{1}))
require.NoError(t, s.Observe([]byte{1}))
})
t.Run("rejects VNC-Auth", func(t *testing.T) {
var s rfbServerStream
require.Error(t, s.Observe([]byte{1, 2}))
})
t.Run("rejects extra types", func(t *testing.T) {
var s rfbServerStream
require.Error(t, s.Observe([]byte{2, 1, 2}))
})
t.Run("rejects a zero-length offer", func(t *testing.T) {
// count 0 is the RFB failure form, not an offer.
var s rfbServerStream
require.Error(t, s.Observe([]byte{0}))
})
}
func TestRFBReadServerHandshake(t *testing.T) {
// The two assertions must run BEFORE the browser socket is upgraded, so
// a failure is still an HTTP status code rather than a close frame. That
// means reading the server's opening bytes off the sandbox connection and
// replaying them afterwards, which is what prelude is for.
t.Run("returns the prelude for replay", func(t *testing.T) {
frames := [][]byte{[]byte("RFB 003.008\n"), {1, 1}}
i := 0
prelude, err := rfbReadServerHandshake(func() ([]byte, error) {
if i >= len(frames) {
return nil, errRFBHandshakeIncomplete
}
f := frames[i]
i++
return f, nil
})
require.NoError(t, err)
require.Equal(t, append([]byte("RFB 003.008\n"), 1, 1), prelude)
})
t.Run("keeps trailing bytes that belong to the message stream", func(t *testing.T) {
// The server may coalesce the handshake with its first real message.
// Those extra bytes must survive into the prelude, or the browser
// never sees them.
one := append([]byte("RFB 003.008\n"), 1, 1, 0xAA, 0xBB)
prelude, err := rfbReadServerHandshake(func() ([]byte, error) { return one, nil })
require.NoError(t, err)
require.Equal(t, one, prelude)
})
t.Run("rejects RFB 3.3", func(t *testing.T) {
_, err := rfbReadServerHandshake(func() ([]byte, error) {
return append([]byte("RFB 003.003\n"), 1, 1), nil
})
require.Error(t, err)
})
t.Run("rejects a non-None security type", func(t *testing.T) {
_, err := rfbReadServerHandshake(func() ([]byte, error) {
return append([]byte("RFB 003.008\n"), 1, 2), nil
})
require.Error(t, err)
})
t.Run("propagates a read failure", func(t *testing.T) {
_, err := rfbReadServerHandshake(func() ([]byte, error) {
return nil, errRFBHandshakeIncomplete
})
require.ErrorIs(t, err, errRFBHandshakeIncomplete)
})
}
func TestRFBClientMessageSize(t *testing.T) {
cases := []struct {
name string
buf []byte
size int
complete bool
known bool
}{
{"SetPixelFormat", append([]byte{0}, make([]byte, 19)...), 20, true, true},
{"SetPixelFormat short", []byte{0, 0, 0}, 20, false, true},
{"SetEncodings 2 encodings", append([]byte{2, 0, 0, 2}, make([]byte, 8)...), 12, true, true},
{"SetEncodings header short", []byte{2, 0}, 0, false, true},
{"FramebufferUpdateRequest", append([]byte{3}, make([]byte, 9)...), 10, true, true},
{"KeyEvent", append([]byte{4}, make([]byte, 7)...), 8, true, true},
{"PointerEvent", append([]byte{5}, make([]byte, 5)...), 6, true, true},
{"ClientCutText 5 bytes", append([]byte{6, 0, 0, 0, 0, 0, 0, 5}, make([]byte, 5)...), 13, true, true},
// noVNC extendedClipboardNotify: length = toUnsigned32bit(-4).
{
"ClientCutText extended 4 bytes",
append([]byte{6, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFC}, 1, 2, 3, 4),
12, true, true,
},
{"EnableContinuousUpdates", append([]byte{150}, make([]byte, 9)...), 10, true, true},
{"ClientFence 4 bytes", append([]byte{248, 0, 0, 0, 0, 0, 0, 0, 4}, make([]byte, 4)...), 13, true, true},
{"SetDesktopSize 1 screen", append([]byte{251, 0, 0, 0, 0, 0, 1, 0}, make([]byte, 16)...), 24, true, true},
{"unknown opcode", []byte{99, 1, 2, 3}, 0, false, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
size, complete, known := rfbClientMessageSize(tc.buf)
require.Equal(t, tc.known, known)
require.Equal(t, tc.complete, complete)
if tc.complete {
require.Equal(t, tc.size, size)
}
})
}
}
func TestRFBOpcodeCountsAsActivity(t *testing.T) {
// Only real user input counts. FramebufferUpdateRequest (3) is driven by
// the server's own updates, so counting it would make a wallpaper with a
// clock look like a person at the keyboard — the whole reason byte
// counting was rejected.
require.True(t, rfbOpcodeCountsAsActivity(4)) // KeyEvent
require.True(t, rfbOpcodeCountsAsActivity(5)) // PointerEvent
require.True(t, rfbOpcodeCountsAsActivity(6)) // ClientCutText
require.False(t, rfbOpcodeCountsAsActivity(0)) // SetPixelFormat
require.False(t, rfbOpcodeCountsAsActivity(2)) // SetEncodings
require.False(t, rfbOpcodeCountsAsActivity(3)) // FramebufferUpdateRequest
require.False(t, rfbOpcodeCountsAsActivity(150))
require.False(t, rfbOpcodeCountsAsActivity(248))
require.False(t, rfbOpcodeCountsAsActivity(251))
}
func TestRFBClientStreamSkipsHandshakeThenDetectsActivity(t *testing.T) {
s := &rfbClientStream{}
// 14 handshake bytes, deliberately split across three chunks so the
// counter cannot assume one frame per read.
require.False(t, s.Consume([]byte("RFB 003.")))
require.False(t, s.Consume([]byte("008\n")))
require.False(t, s.Consume([]byte{1, 1}))
require.True(t, s.ParsingEnabled())
// FramebufferUpdateRequest: parsed, not activity.
require.False(t, s.Consume(append([]byte{3}, make([]byte, 9)...)))
// PointerEvent: activity.
require.True(t, s.Consume(append([]byte{5}, make([]byte, 5)...)))
}
func TestRFBClientStreamHandlesSplitMessages(t *testing.T) {
s := &rfbClientStream{}
require.False(t, s.Consume(append([]byte("RFB 003.008\n"), 1, 1)))
// One KeyEvent delivered one byte at a time.
require.False(t, s.Consume([]byte{4}))
for i := 0; i < 6; i++ {
require.False(t, s.Consume([]byte{0}))
}
require.True(t, s.Consume([]byte{0}), "the final byte completes the KeyEvent")
}
func TestRFBClientStreamHandlesCoalescedMessages(t *testing.T) {
s := &rfbClientStream{}
require.False(t, s.Consume(append([]byte("RFB 003.008\n"), 1, 1)))
// SetPixelFormat (no activity) followed by KeyEvent (activity) in one read.
chunk := append(append([]byte{0}, make([]byte, 19)...), append([]byte{4}, make([]byte, 7)...)...)
require.True(t, s.Consume(chunk))
}
func TestRFBClientStreamFailsClosedOnUnknownOpcode(t *testing.T) {
// Guessing a length would desync the stream forever. The contract is:
// stop parsing, and let the frontend's activity POST take over.
s := &rfbClientStream{}
require.False(t, s.Consume(append([]byte("RFB 003.008\n"), 1, 1)))
require.True(t, s.ParsingEnabled())
require.False(t, s.Consume([]byte{99, 1, 2, 3}))
require.False(t, s.ParsingEnabled(), "unknown opcode must disable parsing for this connection")
// Once disabled it stays disabled, and never reports activity again.
require.False(t, s.Consume(append([]byte{4}, make([]byte, 7)...)))
require.False(t, s.ParsingEnabled())
}
func TestRFBClientStreamKeepsParsingExtendedClipboard(t *testing.T) {
// Extended Clipboard reuses ClientCutText with a negative length field.
// Reading that as unsigned (~4e9) used to Disable() the idle parser for
// the rest of the connection, so a paste (or the caps handshake) left
// idle detection on the frontend POST fallback.
s := &rfbClientStream{}
require.False(t, s.Consume(append([]byte("RFB 003.008\n"), 1, 1)))
notify := append([]byte{6, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFC}, 0, 0, 0, 0)
require.True(t, s.Consume(notify), "extended clipboard is user activity")
require.True(t, s.ParsingEnabled(), "a signed cut-text length must not disable parsing")
require.True(t, s.Consume(append([]byte{5}, make([]byte, 5)...)),
"PointerEvent after an extended paste must still count as activity")
}
func TestRFBClientMessageSizeExtendedClipboardHeaderOnly(t *testing.T) {
// Incomplete body: wait for 4 payload bytes, do not treat the length as
// unknown and Disable().
size, complete, known := rfbClientMessageSize([]byte{6, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFC})
require.True(t, known)
require.False(t, complete)
require.Equal(t, 12, size)
}
func TestRFBClientStreamDoesNotGrowUnbounded(t *testing.T) {
// A truncated ClientCutText claiming a huge length must not let a client
// pin arbitrary memory in the relay.
s := &rfbClientStream{}
require.False(t, s.Consume(append([]byte("RFB 003.008\n"), 1, 1)))
// ClientCutText header claiming ~16 MiB, with no body. 0xFFFFFFFF is a
// signed -1 (extended clipboard of 1 byte) and must NOT take this path.
s.Consume([]byte{6, 0, 0, 0, 0x00, 0xFF, 0xFF, 0xFF})
require.False(t, s.ParsingEnabled(),
"an implausible message length must fail closed rather than buffer")
}
@@ -0,0 +1,954 @@
// Package session provides the sandbox desktop WebSocket relay.
//
// Browser (noVNC, no credentials)
//
// ⇄ this handler ticket auth, 14-byte handshake skip, opcode relay
// ⇄ sandbox gateway e2b-traffic-access-token + Authorization: Basic
// ⇄ websockify :6080 ⇄ x11vnc :5900 (127.0.0.1, -nopw) ⇄ Xvfb ⇄ XFCE
//
// Both credentials exist only on the backend→sandbox hop. The browser holds
// neither, which is the whole reason traffic is relayed rather than sent
// direct.
package session
import (
"context"
stderrors "errors"
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/redis/go-redis/v9"
"academy/internal/application/service"
"academy/internal/common/redislock"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/middleware"
"academy/internal/sandbox"
"academy/internal/types"
)
const (
// desktopBrowserReadLimit bounds one client frame. 4096 (the terminal's
// value) is not enough: a ClientCutText paste exceeds it easily, and
// gorilla closes the connection on overrun rather than truncating.
desktopBrowserReadLimit = 64 * 1024
// desktopSandboxReadLimit bounds one framebuffer-update frame. websockify
// buffers 65536 by default, so 64 KiB would sit exactly on the edge.
desktopSandboxReadLimit = 1024 * 1024
desktopReadTimeout = 120 * time.Second
// desktopHandshakeTimeout bounds the pre-upgrade RFB hello. The relay
// read timeout (120s) was reused here and held the Redis slot for two
// minutes whenever x11vnc was slow; every retry became DESKTOP_BUSY.
desktopHandshakeTimeout = 10 * time.Second
desktopWriteTimeout = 10 * time.Second
desktopPingInterval = 30 * time.Second
)
// Close reasons. SANDBOX_REBUILT is desktop-specific and load-bearing: a
// skill install marks the binding stale, and a desktop reconnect with no
// AgentQA in flight rebuilds the sandbox immediately
// (session_lifecycle.go:190). The user did nothing; someone else clicked
// install in settings. Reconnecting silently into a blank desktop would hide
// that their /workspace scratch is gone.
const (
desktopErrNotBound = "SANDBOX_NOT_BOUND"
desktopErrPaused = "SANDBOX_PAUSED"
desktopErrUnsupported = "DESKTOP_UNSUPPORTED"
desktopErrStartFailed = "DESKTOP_START_FAILED"
desktopErrBusy = "DESKTOP_BUSY"
desktopErrRebuilt = "SANDBOX_REBUILT"
desktopErrUpstream = "DESKTOP_UPSTREAM"
desktopErrIdle = "IDLE_DISCONNECTED"
desktopErrAuth = "AUTH_REVOKED"
desktopErrInternal = "INTERNAL"
)
// desktopUpgrader mirrors terminalUpgrader's CheckOrigin decision and the
// reasoning behind it: authentication travels in an explicit one-shot ticket
// validated before the upgrade, and the endpoint uses no ambient credentials
// (no cookies), so a cross-origin tab cannot piggyback a victim session. A
// strict same-origin check would also break the vite dev proxy, which
// rewrites Host while Origin stays on the dev server.
//
// Buffers are 8x the terminal's because RFB framebuffer updates would
// otherwise be chopped into a great many small writes.
var desktopUpgrader = websocket.Upgrader{
ReadBufferSize: 32 * 1024,
WriteBufferSize: 32 * 1024,
CheckOrigin: func(*http.Request) bool { return true },
Subprotocols: []string{"binary"},
}
// IssueSandboxDesktopTicket mints a one-shot handshake ticket. The access JWT
// stays on this authenticated POST and never reaches the WS URL.
func (h *Handler) IssueSandboxDesktopTicket(c *gin.Context) {
ctx := c.Request.Context()
sessionID := desktopSessionIDParam(c)
if sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})
return
}
if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load session"})
return
}
userID, ok := types.UserIDFromContext(ctx)
if !ok || userID == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok || tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
accessToken := sandboxTerminalBearerToken(c)
if accessToken == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: access token required"})
return
}
record, err := h.userService.GetAccessTokenByValue(ctx, accessToken)
if err != nil || record == nil || strings.TrimSpace(record.ID) == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
if err := service.AssertAccessTokenStillActive(record, userID, time.Now()); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
ticket, err := h.desktopTickets.Issue(ctx, service.SandboxDesktopTicketClaims{
UserID: userID, TenantID: tenantID, SessionID: sessionID, TokenID: record.ID,
})
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to issue ticket"})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"ticket": ticket,
"expires_in": int(service.DefaultSandboxDesktopTicketTTL.Seconds()),
}})
}
// SandboxDesktopWS relays the browser's RFB stream to the session sandbox.
//
// Ticket and auth stay HTTP. Locate may provision but does not start the
// desktop; the operation hold and the exclusive slots come next, then Start.
// Overlay states from locate or start (SANDBOX_NOT_BOUND / SANDBOX_PAUSED /
// DESKTOP_UNSUPPORTED / DESKTOP_START_FAILED) must upgrade and then close
// with a reason: the JS WebSocket API never exposes a failed handshake's
// HTTP status, so a 409 here becomes a generic error overlay instead of
// the confirm card. Handshake prelude failures stay HTTP — by then the
// sandbox is already live and the frontend must not show "create sandbox".
func (h *Handler) SandboxDesktopWS(c *gin.Context) {
sessionID := desktopSessionIDParam(c)
if sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})
return
}
// 1. One-shot ticket. Auth reads the incoming request; workspace identity
// is attached next. Do not capture c.Request.Context() before
// AttachAuthenticatedUser — that snapshot has no tenant, and
// LocateSessionDesktop then fails with "missing workspace context"
// (mapped to DESKTOP_UPSTREAM). SandboxTerminalWS binds ctx after attach
// for the same reason.
claims, err := h.desktopTickets.Consume(c.Request.Context(), c.Query("ticket"))
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid or expired ticket"})
return
}
if claims.SessionID != sessionID {
c.JSON(http.StatusForbidden, gin.H{"error": "ticket is not valid for this session"})
return
}
user, err := h.checkTerminalAuth(c.Request.Context(), service.SandboxTerminalTicketClaims{
UserID: claims.UserID, TenantID: claims.TenantID,
SessionID: claims.SessionID, TokenID: claims.TokenID,
}, true)
if err != nil {
if stderrors.Is(err, service.ErrTerminalAuthDenied) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
logger.ErrorWithFields(c.Request.Context(), err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to validate ticket"})
return
}
if !middleware.AttachAuthenticatedUser(
c, h.tenantService, h.memberService, h.config, user, claims.TenantID,
) {
return
}
ctx := c.Request.Context()
// 2. Locate. Lookup-only unless the user confirmed provision. A bare
// handshake — panel opened, tab restored, background reconnect —
// stays lookup-only: a running sandbox is attached, a paused one
// reports SANDBOX_PAUSED, and a missing one reports SANDBOX_NOT_BOUND.
// Only a confirmed click sets provision=1. This does not start the
// desktop; the request context cancels it if the browser gives up.
allowProvision := terminalFlagParam(c.Query("provision"))
provision := h.terminalProvisionPin(ctx, c, allowProvision)
target, err := h.desktopService.LocateSessionDesktop(ctx, sessionID, provision)
if err != nil {
h.closeDesktopWithError(c, sessionID, allowProvision, "locate", err)
return
}
// 3. Hold the operation first: from here the shared machine cannot be
// rebuilt or reclaimed, so the binding read next names the machine the
// relay will reach.
opCtx, releaseOp, err := target.HoldOperation(ctx)
if err != nil {
c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
return
}
defer releaseOp()
if err := target.FixMachine(opCtx); err != nil {
h.closeDesktopWithError(c, sessionID, allowProvision, "locate", err)
return
}
// 4. One controlling desktop per machine, across replicas. The legacy
// per-session slot is held too, so replicas still on the previous
// release stay mutually exclusive during a rolling upgrade (remove it
// in the following release). Unlike the terminal's 5-per-session
// in-process counter, this must be distributed: two browsers on one
// desktop means two people fighting over one keyboard.
releaseLegacy, gotLegacy, legacyHold, err := h.acquireDesktopSlot(ctx, desktopSlotKey(sessionID))
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to reserve desktop"})
return
}
if !gotLegacy {
c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
return
}
defer releaseLegacy()
releaseSlot, acquired, machineHold, err := h.acquireDesktopSlot(ctx, desktopMachineSlotKey(target.MachineID))
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to reserve desktop"})
return
}
if !acquired {
c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
return
}
defer releaseSlot()
slotHold, stopSlotHold := mergeDesktopHolds(legacyHold, machineHold, opCtx)
defer stopSlotHold()
// Start, dial on the fixed sandbox. The relay context is detached only
// after the browser socket is upgraded. Losing either slot or the
// operation lease cancels this work.
ensureCtx := ctx
if slotHold != nil {
var cancelEnsure context.CancelFunc
ensureCtx, cancelEnsure = context.WithCancel(ctx)
stopEnsureWatch := context.AfterFunc(slotHold, cancelEnsure)
defer stopEnsureWatch()
defer cancelEnsure()
}
desktop, err := h.desktopService.StartSessionDesktop(ensureCtx, target)
if err != nil {
if slotHold != nil && slotHold.Err() != nil {
c.JSON(http.StatusConflict, gin.H{"error": desktopErrBusy})
return
}
_, code := desktopErrorStatus(err)
logger.Warnf(ctx, "[sandbox-desktop] open failed session=%s provision=%t code=%s: %v",
sessionID, allowProvision, code, err)
browserConn, upErr := desktopUpgrader.Upgrade(c.Writer, c.Request, nil)
if upErr != nil {
return
}
writeDesktopProtocolClose(browserConn, code)
return
}
// 4. Read and validate the server's ProtocolVersion while an HTTP status
// code is still expressible: not RFB 003.008 means the client side is
// 13 bytes rather than 14 and the opcode parser would be off by one
// forever. Whatever was read is replayed after the upgrade.
//
// Only the version. The server withholds the security-type list until
// the client answers with its own version, and that answer is noVNC's
// to send — waiting for it here deadlocks until the deadline and looks
// exactly like a dead upstream. The "None and only None" assertion
// moved onto the relay (see desktopRelay.serverStream).
//
// A mute upstream is answered with 502 and nothing else. Tearing the
// stack down from here and redialling was tried and made it worse: the
// browser waits out a second start inside the same upgrade, and the
// healing belongs in StartSessionDesktop, which already ran.
prelude, err := readDesktopServerHandshake(ctx, desktop.Conn)
if err != nil {
_ = desktop.Conn.Close()
logger.Warnf(ctx, "[sandbox-desktop] bad server handshake session=%s: %v", sessionID, err)
c.JSON(http.StatusBadGateway, gin.H{"error": desktopErrUpstream})
return
}
// 5. Only now upgrade the browser socket.
browserConn, err := desktopUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
_ = desktop.Conn.Close()
return
}
relayCtx, cancelRelay := context.WithCancel(context.WithoutCancel(ctx))
// Replay the handshake the browser's noVNC is waiting for.
_ = browserConn.SetWriteDeadline(time.Now().Add(desktopWriteTimeout))
if err := browserConn.WriteMessage(websocket.BinaryMessage, prelude); err != nil {
cancelRelay()
_ = browserConn.Close()
_ = desktop.Conn.Close()
return
}
authClaims := service.SandboxTerminalTicketClaims{
UserID: claims.UserID, TenantID: claims.TenantID,
SessionID: claims.SessionID, TokenID: claims.TokenID,
}
relay := &desktopRelay{
browser: browserConn,
sandbox: desktop.Conn,
ctx: relayCtx,
cancel: cancelRelay,
sessionID: sessionID,
idleDisconnect: desktopIdleDisconnect(desktop),
authCheck: func(checkCtx context.Context) error {
_, err := h.checkTerminalAuth(checkCtx, authClaims, false)
return err
},
}
// Anything the server coalesced onto its version is already the start of
// the security-type list, and the pump will never see it again.
if len(prelude) > rfbProtocolVersionBytes {
if err := relay.serverStream.Observe(prelude[rfbProtocolVersionBytes:]); err != nil {
logger.Warnf(ctx, "[sandbox-desktop] %v session=%s", err, sessionID)
relay.closeWith(desktopErrUpstream)
return
}
}
// A skill install can rebuild the sandbox under a live session
// (session_lifecycle.go:190). Closing with SANDBOX_REBUILT tells the
// frontend the /workspace scratch is gone instead of silently showing
// a blank desktop. The previous sandbox ID lives in Redis so a reconnect
// on another replica still sees the rebuild.
if h.desktopSandboxRebuilt(ctx, sessionID, desktop.SandboxID) {
relay.closeWith(desktopErrRebuilt)
return
}
if slotHold != nil {
stopRelayWatch := context.AfterFunc(slotHold, func() {
relay.closeWith(desktopErrBusy)
})
defer stopRelayWatch()
}
logger.Infof(ctx,
"[sandbox-desktop][audit] open session=%s sandbox=%s user=%s tenant=%d backend=%s",
sessionID, desktop.SandboxID, claims.UserID, claims.TenantID, desktop.Backend)
if desktop.StartTTLRefresh != nil {
desktop.StartTTLRefresh(relayCtx)
}
activeDesktopRelays.Store(sessionID, relay)
defer activeDesktopRelays.Delete(sessionID)
relay.run()
}
// desktopErrorStatus maps an EnsureSessionDesktop failure to an HTTP status
// and a stable code the frontend switches on.
func desktopErrorStatus(err error) (int, string) {
switch {
case stderrors.Is(err, service.ErrDesktopUnsupported),
stderrors.Is(err, sandbox.ErrDesktopUnsupported):
return http.StatusNotImplemented, desktopErrUnsupported
case stderrors.Is(err, service.ErrDesktopStartFailed):
return http.StatusServiceUnavailable, desktopErrStartFailed
case stderrors.Is(err, sandbox.ErrNoLiveSessionSandbox):
return http.StatusConflict, desktopErrNotBound
case stderrors.Is(err, sandbox.ErrSandboxPaused):
return http.StatusConflict, desktopErrPaused
default:
return http.StatusBadGateway, desktopErrUpstream
}
}
// desktopIdleDisconnect is the same workspace window the terminal bridge
// uses. The desktop must not hard-code the 15-minute default: an admin who
// raised TerminalIdleDisconnectSec would otherwise see the two tabs disagree.
func desktopIdleDisconnect(d *service.SessionDesktop) time.Duration {
if d != nil && d.IdleDisconnect > 0 {
return d.IdleDisconnect
}
return sandbox.DefaultTerminalIdleDisconnect
}
func writeDesktopProtocolClose(conn *websocket.Conn, code string) {
if conn == nil {
return
}
reason := strings.TrimSpace(code)
if reason == "" {
reason = desktopErrInternal
}
_ = conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, reason),
time.Now().Add(desktopWriteTimeout),
)
_ = conn.Close()
}
func desktopSessionIDParam(c *gin.Context) string {
if id := strings.TrimSpace(c.Param("id")); id != "" {
return id
}
return strings.TrimSpace(c.Param("session_id"))
}
func readDesktopServerHandshake(ctx context.Context, conn *websocket.Conn) ([]byte, error) {
if conn == nil {
return nil, stderrors.New("desktop handshake: nil conn")
}
handshakeDone := make(chan struct{})
go func() {
select {
case <-ctx.Done():
_ = conn.Close()
case <-handshakeDone:
}
}()
defer close(handshakeDone)
_ = conn.SetReadDeadline(time.Now().Add(desktopHandshakeTimeout))
return rfbReadServerVersion(func() ([]byte, error) {
msgType, payload, rerr := conn.ReadMessage()
if rerr != nil {
return nil, rerr
}
if msgType != websocket.BinaryMessage {
return nil, nil
}
return payload, nil
})
}
// closeDesktopWithError upgrades and closes with the stable code for a
// locate or machine-fix failure. The JS WebSocket API never exposes a failed
// handshake's HTTP status, so overlay states have to ride a close reason.
func (h *Handler) closeDesktopWithError(
c *gin.Context, sessionID string, allowProvision bool, stage string, err error,
) {
ctx := c.Request.Context()
_, code := desktopErrorStatus(err)
logger.Warnf(ctx, "[sandbox-desktop] %s failed session=%s provision=%t code=%s: %v",
stage, sessionID, allowProvision, code, err)
browserConn, upErr := desktopUpgrader.Upgrade(c.Writer, c.Request, nil)
if upErr != nil {
return
}
writeDesktopProtocolClose(browserConn, code)
}
// acquireDesktopSlot reserves one desktop slot across all replicas. key is
// the full Redis key (session or machine); callers build it.
//
// The terminal's per-session cap is a process-local counter, which is
// harmless there (a second shell is a cosmetic problem) and unacceptable here
// (a second desktop is two people on one keyboard). Redis SET NX with a
// renewed lease is the cross-replica version; a crashed replica is covered by
// the lease expiry, not by the release call.
//
// Redis absent means Lite mode, which is one process, so the in-process
// limiter is the correct degradation there.
func (h *Handler) acquireDesktopSlot(
ctx context.Context, key string,
) (release func(), acquired bool, hold context.Context, err error) {
if h.redis == nil {
release, ok := sessionDesktopLimiter.acquire(key)
return release, ok, nil, nil
}
token, err := redislock.NewToken()
if err != nil {
return func() {}, false, nil, err
}
got, err := redislock.TryAcquire(ctx, h.redis, key, token, desktopSlotLease)
if err != nil {
return func() {}, false, nil, err
}
if !got {
return func() {}, false, nil, nil
}
hold, cancelHold := context.WithCancelCause(context.Background())
renewCtx, stopRenew := context.WithCancel(context.WithoutCancel(ctx))
// The timing is read here, before the goroutine starts, so the renew loop
// never reads the package-level settings concurrently with a writer.
go renewDesktopSlot(renewCtx, cancelHold, h.redis, key, token, desktopSlotRenew, desktopSlotLease)
var once sync.Once
return func() {
once.Do(func() {
stopRenew()
cancelHold(nil)
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, _ = redislock.Release(relCtx, h.redis, key, token)
cancel()
})
}, true, hold, nil
}
func renewDesktopSlot(
ctx context.Context,
cancelHold context.CancelCauseFunc,
client redis.UniversalClient,
key, token string,
renewEvery, lease time.Duration,
) {
ticker := time.NewTicker(renewEvery)
defer ticker.Stop()
lastOK := time.Now()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
ok, rerr := redislock.Renew(ctx, client, key, token, lease)
if rerr != nil {
if stderrors.Is(rerr, context.Canceled) && ctx.Err() != nil {
return
}
logger.Warnf(ctx, "[sandbox-desktop] slot renew failed key=%s: %v", key, rerr)
if time.Since(lastOK) >= lease {
cancelHold(rerr)
return
}
continue
}
if !ok {
cancelHold(redislock.ErrLockOwnershipLost)
return
}
lastOK = time.Now()
}
}
}
var (
// desktopSlotLease outlives a network blip; desktopSlotRenew keeps it
// alive while the relay runs. Tests shorten both so a stolen or expired
// key is observed without waiting on the production 90s lease.
desktopSlotLease = 90 * time.Second
desktopSlotRenew = 30 * time.Second
)
func desktopSlotKey(sessionID string) string {
return "academy:desktop-slot:" + sessionID
}
func desktopMachineSlotKey(machineID string) string {
return "academy:desktop-slot:machine:" + machineID
}
// mergeDesktopHolds ends as soon as any hold ends. Nil holds (no Redis) are
// ignored; with none left it returns nil, as a single missing hold did. The
// stop function ends the merged context; the caller defers it once the relay
// is done, which also satisfies go vet's lostcancel check on cancel vars
// whose only other use sits inside a loop body.
func mergeDesktopHolds(holds ...context.Context) (context.Context, func()) {
var live []context.Context
for _, h := range holds {
if h != nil {
live = append(live, h)
}
}
if len(live) == 0 {
return nil, func() {}
}
merged, cancel := context.WithCancelCause(context.Background())
for _, h := range live {
context.AfterFunc(h, func() { cancel(context.Cause(h)) })
}
return merged, func() { cancel(context.Canceled) }
}
// desktopLimiter caps one key to one desktop within this process. The key is
// the full slot key, so a machine and a session do not share an entry.
type desktopLimiter struct {
mu sync.Mutex
open map[string]bool
}
var sessionDesktopLimiter = &desktopLimiter{open: make(map[string]bool)}
func (l *desktopLimiter) acquire(key string) (func(), bool) {
l.mu.Lock()
defer l.mu.Unlock()
if l.open[key] {
return func() {}, false
}
l.open[key] = true
released := false
return func() {
l.mu.Lock()
defer l.mu.Unlock()
if !released {
released = true
delete(l.open, key)
}
}, true
}
// desktopRelay forwards frames in both directions and judges idleness from
// the client message stream.
type desktopRelay struct {
browser *websocket.Conn
sandbox *websocket.Conn
ctx context.Context
cancel context.CancelFunc
sessionID string
stream rfbClientStream
// serverStream carries the security-type assertion that used to run
// before the upgrade. See rfbProtocolVersionBytes for why it had to move.
serverStream rfbServerStream
mu sync.Mutex
lastActivity time.Time
// idleDisconnect is how long the desktop may go without a client
// KeyEvent / PointerEvent / ClientCutText before the relay closes. It
// reuses the workspace's terminal setting: both exist to let a sandbox
// reach its provider TTL once the human walked away.
idleDisconnect time.Duration
// authCheck re-validates the handshake identity on the same cadence as
// the terminal. Handshake is a snapshot; this is what closes the window
// after logout, token revocation, or being removed from the workspace.
// Nil disables the watcher. rejectExpired must stay false: axios rotates
// access tokens without revoking the row the ticket was bound to.
authCheck func(context.Context) error
}
func (r *desktopRelay) run() {
defer r.cancel()
defer func() { _ = r.browser.Close() }()
defer func() { _ = r.sandbox.Close() }()
r.browser.SetReadLimit(desktopBrowserReadLimit)
r.sandbox.SetReadLimit(desktopSandboxReadLimit)
r.browser.SetPongHandler(func(string) error {
return r.browser.SetReadDeadline(time.Now().Add(desktopReadTimeout))
})
r.sandbox.SetPongHandler(func(string) error {
return r.sandbox.SetReadDeadline(time.Now().Add(desktopReadTimeout))
})
r.touch()
done := make(chan struct{})
var once sync.Once
finish := func() { once.Do(func() { close(done) }) }
// The sandbox pump is not the goroutine run() waits on. If it just
// returns, pumpBrowserToSandbox stays blocked on a live browser read
// until desktopReadTimeout, and the Redis slot stays held (DESKTOP_BUSY
// on every reconnect). Closing both hops unblocks that read immediately.
go func() {
defer finish()
defer r.closePeers()
r.pumpSandboxToBrowser()
}()
go r.watchIdle(done)
go r.watchContext(done)
go r.heartbeat(done)
go r.watchAuth(done)
r.pumpBrowserToSandbox()
finish()
}
// pumpBrowserToSandbox forwards client frames and feeds the opcode parser.
//
// Note what is NOT here: ping/pong forwarding. gorilla does not surface
// received pings as messages, so each hop keeps its own liveness. That is the
// correct behaviour, and it is written down because it looks like an omission.
func (r *desktopRelay) pumpBrowserToSandbox() {
for {
_ = r.browser.SetReadDeadline(time.Now().Add(desktopReadTimeout))
msgType, payload, err := r.browser.ReadMessage()
if err != nil {
return
}
if msgType != websocket.BinaryMessage {
continue
}
parsing := r.stream.ParsingEnabled()
if r.stream.Consume(payload) {
r.touch()
}
if parsing && !r.stream.ParsingEnabled() {
logger.Warnf(r.ctx,
"[sandbox-desktop] RFB client parser disabled; falling back to reported activity session=%s",
r.sessionID)
}
_ = r.sandbox.SetWriteDeadline(time.Now().Add(desktopWriteTimeout))
if err := r.sandbox.WriteMessage(websocket.BinaryMessage, payload); err != nil {
return
}
}
}
func (r *desktopRelay) pumpSandboxToBrowser() {
for {
_ = r.sandbox.SetReadDeadline(time.Now().Add(desktopReadTimeout))
msgType, payload, err := r.sandbox.ReadMessage()
if err != nil {
return
}
if msgType != websocket.BinaryMessage {
continue
}
if err := r.serverStream.Observe(payload); err != nil {
logger.Warnf(r.ctx, "[sandbox-desktop] %v session=%s", err, r.sessionID)
r.closeWith(desktopErrUpstream)
return
}
_ = r.browser.SetWriteDeadline(time.Now().Add(desktopWriteTimeout))
if err := r.browser.WriteMessage(websocket.BinaryMessage, payload); err != nil {
return
}
}
}
func (r *desktopRelay) touch() {
r.mu.Lock()
r.lastActivity = time.Now()
r.mu.Unlock()
}
func (r *desktopRelay) idleFor(now time.Time) time.Duration {
r.mu.Lock()
defer r.mu.Unlock()
return now.Sub(r.lastActivity)
}
func (r *desktopRelay) isIdle(now time.Time) bool {
if r.idleDisconnect <= 0 {
return false
}
return r.idleFor(now) >= r.idleDisconnect
}
// watchIdle closes the relay once nobody has touched the desktop for
// idleDisconnect. closePeers cancels relayCtx, which stops the
// StartTTLRefresh loop started after upgrade — that is what finally lets
// the sandbox pause on its own provider timeout.
func (r *desktopRelay) watchIdle(done <-chan struct{}) {
if r.idleDisconnect <= 0 {
return
}
// Check often enough that the reported idle time is roughly honest,
// cheaply enough that it is free.
interval := r.idleDisconnect / 10
if interval < time.Second {
interval = time.Second
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-r.ctx.Done():
return
case now := <-ticker.C:
if r.isIdle(now) {
r.closeWith(desktopErrIdle)
return
}
}
}
}
// watchContext unblocks run() when the relay ctx is canceled from outside
// the pumps — notably when the Redis slot hold is lost. closePeers is what
// unblocks ReadMessage; canceling ctx alone would sit on desktopReadTimeout.
func (r *desktopRelay) watchContext(done <-chan struct{}) {
select {
case <-done:
case <-r.ctx.Done():
r.closePeers()
}
}
// heartbeat keeps the browser hop alive. Each hop pings independently: this
// relay does not forward ping/pong, because gorilla does not surface received
// pings as messages. See pumpBrowserToSandbox.
func (r *desktopRelay) heartbeat(done <-chan struct{}) {
ticker := time.NewTicker(desktopPingInterval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-r.ctx.Done():
return
case <-ticker.C:
_ = r.browser.WriteControl(websocket.PingMessage, nil,
time.Now().Add(desktopWriteTimeout))
_ = r.sandbox.WriteControl(websocket.PingMessage, nil,
time.Now().Add(desktopWriteTimeout))
}
}
}
// watchAuth re-validates the minting identity while the desktop is open.
// Denied (logout / revoke / membership loss) tears the relay down; any other
// error is a lookup failure and is retried, matching the terminal so a
// database hiccup cannot disconnect every open desktop at once.
func (r *desktopRelay) watchAuth(done <-chan struct{}) {
if r == nil || r.authCheck == nil {
return
}
ticker := time.NewTicker(terminalAuthRecheckInterval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-r.ctx.Done():
return
case <-ticker.C:
checkCtx, cancel := context.WithTimeout(r.ctx, terminalAuthRecheckTimeout)
err := r.authCheck(checkCtx)
cancel()
if err == nil {
continue
}
if r.ctx.Err() != nil {
return
}
if stderrors.Is(err, service.ErrTerminalAuthDenied) {
r.closeWith(desktopErrAuth)
return
}
logger.Warnf(r.ctx, "[sandbox-desktop] auth recheck failed session=%s: %v",
r.sessionID, err)
}
}
}
// closeWith sends a close frame carrying a stable reason code, so the
// frontend can show the right message instead of silently reconnecting.
func (r *desktopRelay) closeWith(reason string) {
if r != nil && r.browser != nil {
_ = r.browser.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, reason),
time.Now().Add(desktopWriteTimeout))
}
r.closePeers()
}
// closePeers tears down both hops. gorilla's Close unblocks a ReadMessage
// on the other side, which is what lets run() return (and release the
// desktop slot) instead of sitting on desktopReadTimeout.
func (r *desktopRelay) closePeers() {
if r == nil {
return
}
if r.cancel != nil {
r.cancel()
}
if r.browser != nil {
_ = r.browser.Close()
}
if r.sandbox != nil {
_ = r.sandbox.Close()
}
}
// TouchFromFrontend records the activity signal the browser POSTs. It is the
// only source once the opcode parser has fallen back (unknown opcode). While
// the parser is healthy this is a no-op: a client that kept posting would
// otherwise ride the TTL without generating KeyEvent/PointerEvent.
func (r *desktopRelay) TouchFromFrontend() {
if r == nil || r.stream.ParsingEnabled() {
return
}
r.touch()
}
// ReportSandboxDesktopActivity records browser-side key/mouse activity.
//
// It is the fallback the RFB parser degrades to on an unknown opcode, and a
// no-op when the parser is healthy. It is deliberately not the primary
// signal: a client that simply stops posting would keep the sandbox alive
// for free.
func (h *Handler) ReportSandboxDesktopActivity(c *gin.Context) {
sessionID := desktopSessionIDParam(c)
if sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})
return
}
if _, err := h.sessionService.GetOwnedSession(c.Request.Context(), sessionID); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
}
touchDesktopRelay(sessionID)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// activeDesktopRelays lets the activity endpoint reach the live relay. It is
// process-local by nature: the POST and the WebSocket ride the same sticky
// connection in practice, and a miss only costs one skipped touch.
var activeDesktopRelays sync.Map // sessionID -> *desktopRelay
func touchDesktopRelay(sessionID string) {
if value, ok := activeDesktopRelays.Load(sessionID); ok {
if relay, ok := value.(*desktopRelay); ok {
relay.TouchFromFrontend()
}
}
}
// desktopSandboxRebuilt records the sandbox this session's desktop just
// attached to and reports whether it differs from the previous one.
func (h *Handler) desktopSandboxRebuilt(ctx context.Context, sessionID, sandboxID string) bool {
if h == nil || h.desktopLast == nil {
return false
}
sessionID = strings.TrimSpace(sessionID)
sandboxID = strings.TrimSpace(sandboxID)
if sessionID == "" || sandboxID == "" {
return false
}
prev, err := h.desktopLast.Get(ctx, sessionID)
if err != nil {
logger.Warnf(ctx, "[sandbox-desktop] last-sandbox get failed session=%s: %v", sessionID, err)
}
if setErr := h.desktopLast.Set(ctx, sessionID, sandboxID); setErr != nil {
logger.Warnf(ctx, "[sandbox-desktop] last-sandbox set failed session=%s: %v", sessionID, setErr)
}
return prev != "" && prev != sandboxID
}
@@ -0,0 +1,469 @@
package session
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/gorilla/websocket"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"academy/internal/application/service"
"academy/internal/sandbox"
)
func TestDesktopRelayIdleFiresWithoutOpcodeActivity(t *testing.T) {
// The control this whole design exists for: a desktop nobody is touching
// must go idle even though bytes keep flowing (XFCE clock, websockify
// heartbeat, ContinuousUpdates).
relay := &desktopRelay{sessionID: "sess-1", idleDisconnect: 50 * time.Millisecond}
relay.touch()
// Feed traffic that is NOT activity: handshake, then repeated
// FramebufferUpdateRequest.
relay.stream.Consume(append([]byte("RFB 003.008\n"), 1, 1))
for i := 0; i < 20; i++ {
require.False(t, relay.stream.Consume(append([]byte{3}, make([]byte, 9)...)))
}
time.Sleep(80 * time.Millisecond)
require.True(t, relay.idleFor(time.Now()) >= 50*time.Millisecond)
require.True(t, relay.isIdle(time.Now()))
}
func TestDesktopRelayNotIdleAfterPointerEvent(t *testing.T) {
relay := &desktopRelay{sessionID: "sess-1", idleDisconnect: time.Minute}
relay.stream.Consume(append([]byte("RFB 003.008\n"), 1, 1))
if relay.stream.Consume(append([]byte{5}, make([]byte, 5)...)) {
relay.touch()
}
require.False(t, relay.isIdle(time.Now()))
}
func TestDesktopRelayFrontendReportKeepsAliveAfterParserFallback(t *testing.T) {
// After an unknown opcode the parser is off for good, so the frontend POST
// is the only remaining activity source.
relay := &desktopRelay{sessionID: "sess-1", idleDisconnect: time.Minute}
relay.stream.Consume(append([]byte("RFB 003.008\n"), 1, 1))
relay.stream.Consume([]byte{99, 0, 0})
require.False(t, relay.stream.ParsingEnabled())
relay.lastActivity = time.Now().Add(-2 * time.Minute)
require.True(t, relay.isIdle(time.Now()))
relay.TouchFromFrontend()
require.False(t, relay.isIdle(time.Now()))
}
func TestDesktopRelayFrontendReportIsIgnoredWhileParserHealthy(t *testing.T) {
relay := &desktopRelay{sessionID: "sess-1", idleDisconnect: time.Minute}
relay.stream.Consume(append([]byte("RFB 003.008\n"), 1, 1))
require.True(t, relay.stream.ParsingEnabled())
relay.lastActivity = time.Now().Add(-2 * time.Minute)
require.True(t, relay.isIdle(time.Now()))
relay.TouchFromFrontend()
require.True(t, relay.isIdle(time.Now()),
"a healthy parser must ignore the activity POST so a client cannot keep the TTL by posting")
}
func TestDesktopSandboxRebuiltUsesStore(t *testing.T) {
h := &Handler{desktopLast: service.NewSandboxDesktopLastStore(nil)}
ctx := context.Background()
require.False(t, h.desktopSandboxRebuilt(ctx, "sess-1", "sbx-a"))
require.True(t, h.desktopSandboxRebuilt(ctx, "sess-1", "sbx-b"))
require.False(t, h.desktopSandboxRebuilt(ctx, "sess-1", "sbx-b"))
}
func TestDesktopSlotIsExclusivePerSession(t *testing.T) {
first, ok := sessionDesktopLimiter.acquire("sess-excl")
require.True(t, ok)
_, ok = sessionDesktopLimiter.acquire("sess-excl")
require.False(t, ok, "a second desktop on one session means two people on one keyboard")
first()
third, ok := sessionDesktopLimiter.acquire("sess-excl")
require.True(t, ok, "releasing must free the slot")
third()
}
func TestDesktopSlotIsExclusivePerMachineAcrossSessions(t *testing.T) {
h, _, _ := newDesktopSlotHandler(t)
ctx := context.Background()
key := desktopMachineSlotKey("machine-1")
release, got, _, err := h.acquireDesktopSlot(ctx, key)
require.NoError(t, err)
require.True(t, got)
_, got, _, err = h.acquireDesktopSlot(ctx, key)
require.NoError(t, err)
require.False(t, got, "a second session on the same machine gets DESKTOP_BUSY")
release()
_, got, _, err = h.acquireDesktopSlot(ctx, desktopMachineSlotKey("machine-2"))
require.NoError(t, err)
require.True(t, got)
}
func TestMergeDesktopHoldsEndsWithAnyHold(t *testing.T) {
a, cancelA := context.WithCancel(context.Background())
b, cancelB := context.WithCancel(context.Background())
defer cancelB()
merged, stopMerged := mergeDesktopHolds(a, nil, b)
defer stopMerged()
cancelA()
require.Eventually(t, func() bool { return merged.Err() != nil }, time.Second, 5*time.Millisecond)
none, stopNone := mergeDesktopHolds(nil, nil)
require.Nil(t, none)
stopNone()
}
func TestDesktopSlotReleaseIsIdempotent(t *testing.T) {
release, ok := sessionDesktopLimiter.acquire("sess-idem")
require.True(t, ok)
release()
release()
next, ok := sessionDesktopLimiter.acquire("sess-idem")
require.True(t, ok)
next()
}
func withDesktopSlotTiming(t *testing.T, lease, renew time.Duration) {
t.Helper()
origLease, origRenew := desktopSlotLease, desktopSlotRenew
desktopSlotLease, desktopSlotRenew = lease, renew
t.Cleanup(func() {
desktopSlotLease, desktopSlotRenew = origLease, origRenew
})
}
func newDesktopSlotHandler(t *testing.T) (*Handler, *miniredis.Miniredis, *redis.Client) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { require.NoError(t, client.Close()) })
return &Handler{redis: client}, mini, client
}
func TestDesktopSlotRenewSurvivesTransientRedisError(t *testing.T) {
withDesktopSlotTiming(t, 400*time.Millisecond, 50*time.Millisecond)
h, mini, client := newDesktopSlotHandler(t)
ctx := context.Background()
release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-blip"))
require.NoError(t, err)
require.True(t, got)
require.NotNil(t, hold)
defer release()
mini.SetError("timeout")
time.Sleep(70 * time.Millisecond)
mini.SetError("")
for i := 0; i < 6; i++ {
time.Sleep(70 * time.Millisecond)
mini.FastForward(80 * time.Millisecond)
}
select {
case <-hold.Done():
t.Fatal("a redis blip must not drop the desktop slot")
default:
}
require.NotEmpty(t, client.Get(ctx, desktopSlotKey("sess-blip")).Val())
_, got, _, err = h.acquireDesktopSlot(ctx, desktopSlotKey("sess-blip"))
require.NoError(t, err)
require.False(t, got, "the original relay must still own the slot after a blip")
}
func TestDesktopSlotCancelsHoldWhenRedisStaysDownPastLease(t *testing.T) {
withDesktopSlotTiming(t, 200*time.Millisecond, 40*time.Millisecond)
h, mini, _ := newDesktopSlotHandler(t)
ctx := context.Background()
release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-down"))
require.NoError(t, err)
require.True(t, got)
defer release()
mini.SetError("timeout")
select {
case <-hold.Done():
case <-time.After(time.Second):
t.Fatal("redis down for a full lease must drop the hold; " +
"otherwise a recovered replica would still claim exclusivity")
}
}
func TestDesktopSlotCancelsHoldWhenOwnershipIsStolen(t *testing.T) {
withDesktopSlotTiming(t, 400*time.Millisecond, 40*time.Millisecond)
h, _, client := newDesktopSlotHandler(t)
ctx := context.Background()
release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-stolen"))
require.NoError(t, err)
require.True(t, got)
defer release()
require.NoError(t, client.Set(ctx, desktopSlotKey("sess-stolen"), "intruder", time.Minute).Err())
select {
case <-hold.Done():
case <-time.After(300 * time.Millisecond):
t.Fatal("losing the redis key must cancel the hold so the relay can drop")
}
second, got, secondHold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-stolen"))
require.NoError(t, err)
require.False(t, got, "the thief still owns the key; we must not overwrite it")
_ = second
_ = secondHold
}
func TestDesktopSlotCancelsHoldWhenKeyExpires(t *testing.T) {
withDesktopSlotTiming(t, 400*time.Millisecond, 40*time.Millisecond)
h, _, client := newDesktopSlotHandler(t)
ctx := context.Background()
release, got, hold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-expired"))
require.NoError(t, err)
require.True(t, got)
defer release()
require.NoError(t, client.Del(ctx, desktopSlotKey("sess-expired")).Err())
select {
case <-hold.Done():
case <-time.After(300 * time.Millisecond):
t.Fatal("an expired slot must cancel the hold; otherwise a second client can join")
}
second, got, secondHold, err := h.acquireDesktopSlot(ctx, desktopSlotKey("sess-expired"))
require.NoError(t, err)
require.True(t, got, "after the first hold is lost the session must accept one new desktop")
defer second()
_ = secondHold
}
func TestDesktopIdleDisconnectFollowsWorkspaceTerminalSetting(t *testing.T) {
require.Equal(t, time.Hour, desktopIdleDisconnect(&service.SessionDesktop{
IdleDisconnect: time.Hour,
}))
require.Equal(t, sandbox.DefaultTerminalIdleDisconnect, desktopIdleDisconnect(&service.SessionDesktop{}))
require.Equal(t, sandbox.DefaultTerminalIdleDisconnect, desktopIdleDisconnect(nil))
}
func TestDesktopHandshakeTimeoutIsShorterThanRelayReadTimeout(t *testing.T) {
// Reusing the 120s relay read deadline for the pre-upgrade RFB hello held
// the Redis slot for two minutes; retries became DESKTOP_BUSY. The hello
// is 12 bytes as soon as x11vnc accepts, so a short bound is enough.
require.Greater(t, desktopReadTimeout, desktopHandshakeTimeout)
require.LessOrEqual(t, desktopHandshakeTimeout, 15*time.Second)
}
func TestDesktopErrorStatusMapsLookupFailures(t *testing.T) {
status, code := desktopErrorStatus(sandbox.ErrNoLiveSessionSandbox)
require.Equal(t, http.StatusConflict, status)
require.Equal(t, desktopErrNotBound, code)
status, code = desktopErrorStatus(sandbox.ErrSandboxPaused)
require.Equal(t, http.StatusConflict, status)
require.Equal(t, desktopErrPaused, code)
status, code = desktopErrorStatus(service.ErrDesktopUnsupported)
require.Equal(t, http.StatusNotImplemented, status)
require.Equal(t, desktopErrUnsupported, code)
status, code = desktopErrorStatus(service.ErrDesktopStartFailed)
require.Equal(t, http.StatusServiceUnavailable, status)
require.Equal(t, desktopErrStartFailed, code)
}
func TestSandboxDesktopWSLookupIsOptInProvision(t *testing.T) {
// Opening the panel is a GET. Creating or resuming a microVM must stay
// behind an explicit provision=1, the same contract as the terminal tab.
src, err := os.ReadFile("sandbox_desktop_ws.go")
require.NoError(t, err)
text := string(src)
require.Contains(t, text, `allowProvision := terminalFlagParam(c.Query("provision"))`)
// Locate runs before either slot exists, so the pin uses the request
// context. Start is what ensureCtx (the slot hold) cancels.
require.Contains(t, text, `h.terminalProvisionPin(ctx, c, allowProvision)`)
require.NotContains(t, text, `terminalProvisionPin(ctx, c, true)`)
// The JS WebSocket API never exposes a failed handshake's HTTP status.
// Overlay states (not bound / paused) have to ride a close reason after
// upgrade, or the panel shows a generic error instead of the confirm card.
require.Contains(t, text, "writeDesktopProtocolClose")
}
func TestDesktopRelayTearsDownWhenAuthIsRevoked(t *testing.T) {
prev := terminalAuthRecheckInterval
terminalAuthRecheckInterval = 20 * time.Millisecond
t.Cleanup(func() { terminalAuthRecheckInterval = prev })
browserClient, sandboxClient, runReturned, _ := startDesktopRelay(t, func(context.Context) error {
return service.ErrTerminalAuthDenied
})
select {
case <-runReturned:
case <-time.After(2 * time.Second):
t.Fatal("run() still blocked after auth was revoked; the desktop would keep relaying")
}
require.NoError(t, browserClient.SetReadDeadline(time.Now().Add(2*time.Second)))
_, _, err := browserClient.ReadMessage()
var closeErr *websocket.CloseError
require.ErrorAs(t, err, &closeErr)
require.Equal(t, desktopErrAuth, closeErr.Text)
require.NoError(t, sandboxClient.SetReadDeadline(time.Now().Add(2*time.Second)))
_, _, err = sandboxClient.ReadMessage()
require.Error(t, err, "sandbox hop must close with the browser when auth is revoked")
}
func TestDesktopRelaySurvivesTransientAuthLookupFailure(t *testing.T) {
prev := terminalAuthRecheckInterval
terminalAuthRecheckInterval = 10 * time.Millisecond
t.Cleanup(func() { terminalAuthRecheckInterval = prev })
var checks atomic.Int32
browserClient, _, runReturned, _ := startDesktopRelay(t, func(context.Context) error {
checks.Add(1)
return errors.New("db down")
})
require.Eventually(t, func() bool {
return checks.Load() >= 3
}, 2*time.Second, 10*time.Millisecond, "watcher must keep retrying")
select {
case <-runReturned:
t.Fatal("a lookup failure must not tear the desktop down")
case <-time.After(50 * time.Millisecond):
}
require.NoError(t, browserClient.SetReadDeadline(time.Now().Add(150*time.Millisecond)))
_, _, err := browserClient.ReadMessage()
require.Error(t, err)
netErr, ok := err.(interface{ Timeout() bool })
require.True(t, ok && netErr.Timeout(),
"expected a read timeout (desktop still open), got %v", err)
}
func TestSandboxDesktopWSWiresLiveAuthRecheck(t *testing.T) {
src, err := os.ReadFile("sandbox_desktop_ws.go")
require.NoError(t, err)
text := string(src)
require.Contains(t, text, "authCheck:")
require.Contains(t, text, "checkTerminalAuth(checkCtx, authClaims, false)")
require.Contains(t, text, "go r.watchAuth(done)")
require.Contains(t, text, "go r.watchContext(done)")
}
func TestSandboxDesktopWSStartsTTLRefreshOnRelayCtx(t *testing.T) {
src, err := os.ReadFile("sandbox_desktop_ws.go")
require.NoError(t, err)
text := string(src)
require.Contains(t, text, "desktop.StartTTLRefresh(relayCtx)")
}
func TestSandboxDesktopWSDoesNotRefreshProviderTTL(t *testing.T) {
// The relay must not run its own SetTimeout loop. Cube/E2B refresh is
// started on relayCtx via StartTTLRefresh after upgrade.
src, err := os.ReadFile("sandbox_desktop_ws.go")
require.NoError(t, err)
text := string(src)
require.NotContains(t, text, "ttlRefresh func")
require.NotContains(t, text, "go r.refreshTTL")
require.NotContains(t, text, "func (r *desktopRelay) refreshTTL")
}
func TestDesktopRelaySandboxDropReleasesWithoutReadTimeout(t *testing.T) {
// The Redis desktop slot lives until run() returns. If the sandbox hop
// dies and run() waits out desktopReadTimeout on the still-open browser
// read, every reconnect is DESKTOP_BUSY for up to two minutes.
browserClient, sandboxClient, runReturned, _ := startDesktopRelay(t, nil)
require.NoError(t, sandboxClient.Close())
select {
case <-runReturned:
case <-time.After(2 * time.Second):
t.Fatal("run() still blocked after the sandbox hop dropped; " +
"the desktop slot would stay held for desktopReadTimeout")
}
require.NoError(t, browserClient.SetReadDeadline(time.Now().Add(2*time.Second)))
_, _, err := browserClient.ReadMessage()
require.Error(t, err, "the browser hop must close so noVNC disconnects and can reconnect")
}
func TestDesktopRelayUnblocksWhenContextCanceled(t *testing.T) {
// cancel() alone does not unblock gorilla ReadMessage. watchContext must
// closePeers or run() sits on desktopReadTimeout and the Redis slot stays held.
_, _, runReturned, cancel := startDesktopRelay(t, nil)
cancel()
select {
case <-runReturned:
case <-time.After(2 * time.Second):
t.Fatal("run() still blocked after ctx cancel; watchContext must close both hops")
}
}
func startDesktopRelay(t *testing.T, authCheck func(context.Context) error) (
browserClient, sandboxClient *websocket.Conn, runReturned <-chan struct{}, cancel context.CancelFunc,
) {
t.Helper()
browserSrvConn := make(chan *websocket.Conn, 1)
sandboxSrvConn := make(chan *websocket.Conn, 1)
browserSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := desktopUpgrader.Upgrade(w, r, nil)
if err != nil {
return
}
browserSrvConn <- conn
}))
t.Cleanup(browserSrv.Close)
sandboxSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := desktopUpgrader.Upgrade(w, r, nil)
if err != nil {
return
}
sandboxSrvConn <- conn
}))
t.Cleanup(sandboxSrv.Close)
var err error
browserClient, _, err = websocket.DefaultDialer.Dial(
"ws"+strings.TrimPrefix(browserSrv.URL, "http"), nil)
require.NoError(t, err)
t.Cleanup(func() { _ = browserClient.Close() })
sandboxClient, _, err = websocket.DefaultDialer.Dial(
"ws"+strings.TrimPrefix(sandboxSrv.URL, "http"), nil)
require.NoError(t, err)
t.Cleanup(func() { _ = sandboxClient.Close() })
var ctx context.Context
ctx, cancel = context.WithCancel(context.Background())
t.Cleanup(cancel)
relay := &desktopRelay{
browser: <-browserSrvConn,
sandbox: <-sandboxSrvConn,
ctx: ctx,
cancel: cancel,
sessionID: "sess-pump",
idleDisconnect: 0,
authCheck: authCheck,
}
done := make(chan struct{})
go func() {
defer close(done)
relay.run()
}()
return browserClient, sandboxClient, done, cancel
}
@@ -0,0 +1,343 @@
// Package session: terminal bridge between the WebSocket and the sandbox
// PTY (see sandbox_terminal_ws.go for the protocol contract).
package session
import (
"context"
"encoding/json"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"academy/internal/application/service"
"academy/internal/logger"
)
// terminalBridge owns one upgraded terminal connection. Exactly one of the
// goroutines it starts (output pump, input pump, heartbeat, idle, auth recheck)
// observes termination and drives cleanup; the others exit as a side effect of
// the shared teardown.
type terminalBridge struct {
conn *websocket.Conn
ctx context.Context
cancel context.CancelFunc
session string
terminal *service.SessionTerminal
// idleDisconnect is how long to wait without PTY activity. Zero disables
// the watcher (should not happen: the service always supplies a default).
idleDisconnect time.Duration
lastActivity atomic.Int64
// authCheck re-validates the handshake identity. It returns
// service.ErrTerminalAuthDenied when access is definitively gone and any
// other error for a lookup failure worth retrying. Nil disables the
// watcher. A closure rather than the Handler: the bridge needs exactly
// this one capability, and holding the handler would give it the whole
// dependency graph (and make watchAuth untestable).
authCheck func(context.Context) error
// writeMu serialises writes: the output pump streams PTY bytes while
// control frames (ready/error/exited) come from the pump goroutines.
writeMu sync.Mutex
// teardown runs once, from whichever goroutine observes the end.
teardownOnce sync.Once
// teardownReason records why the bridge ended, for the closing log line.
teardownReason string
}
// teardownWith records the reason and tears the bridge down.
func (b *terminalBridge) teardownWith(reason string) {
b.teardownOnce.Do(func() {
b.teardownReason = reason
b.teardownLocked()
})
}
func (b *terminalBridge) run() {
pid := b.terminal.Session.PID()
reattachable := pid > 0
b.sendControl(terminalControlFrame{
Type: "ready",
PID: pid,
Backend: b.terminal.Backend,
Reattachable: &reattachable,
})
// Liveness defaults; the read loop also refreshes on every frame.
b.conn.SetReadLimit(terminalMaxInputBytes)
_ = b.conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))
b.conn.SetPongHandler(func(string) error {
return b.conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))
})
b.touchActivity()
done := make(chan struct{})
go b.pumpOutput(done)
go b.heartbeat(done)
go b.watchIdle(done)
go b.watchAuth(done)
b.pumpInput()
b.teardownWith("client_disconnected")
<-done
}
// sendControl writes one JSON control frame. Safe for concurrent use.
func (b *terminalBridge) sendControl(frame terminalControlFrame) {
payload, err := json.Marshal(frame)
if err != nil {
return
}
b.writeMu.Lock()
defer b.writeMu.Unlock()
// The deadline is set under the same lock as the write: it is connection
// state, and the output pump shares this connection.
_ = b.conn.SetWriteDeadline(time.Now().Add(terminalWriteTimeout))
if werr := b.conn.WriteMessage(websocket.TextMessage, payload); werr != nil {
logger.Debugf(b.ctx, "[sandbox-terminal] control write failed session=%s: %v",
b.session, werr)
}
}
// pumpOutput streams PTY output to the browser as binary frames. It exits
// when the terminal's output channel closes; teardown has already been
// triggered by then (or triggers now via the closing path in run()).
func (b *terminalBridge) pumpOutput(done chan struct{}) {
defer close(done)
// Normal termination: the channel closed because we tore the bridge down
// from another goroutine. Any other exit path below sets a real reason.
defer b.teardownWith("stream_closed")
for event := range b.terminal.Session.Output() {
switch {
case event.Err != nil:
logger.Warnf(b.ctx, "[sandbox-terminal] stream error session=%s: %v",
b.session, event.Err)
b.sendControl(terminalControlFrame{
Type: "error",
Code: terminalErrInternal,
Message: "terminal stream failed",
})
b.teardownWith("stream_error")
return
case event.Exited:
code := event.ExitCode
b.sendControl(terminalControlFrame{Type: "exited", ExitCode: &code})
b.teardownWith("shell_exited")
return
case len(event.Data) > 0:
b.touchActivity()
b.writeMu.Lock()
_ = b.conn.SetWriteDeadline(time.Now().Add(terminalWriteTimeout))
if err := b.conn.WriteMessage(websocket.BinaryMessage, event.Data); err != nil {
b.writeMu.Unlock()
logger.Debugf(b.ctx, "[sandbox-terminal] output write failed session=%s: %v",
b.session, err)
b.teardownWith("output_write_failed")
return
}
b.writeMu.Unlock()
}
}
}
// pumpInput reads browser frames until the connection dies: binary frames
// are keystrokes, text frames are resize/ping control requests.
func (b *terminalBridge) pumpInput() {
for {
messageType, payload, err := b.conn.ReadMessage()
if err != nil {
// Normal close or transport failure — both end the session.
return
}
_ = b.conn.SetReadDeadline(time.Now().Add(terminalReadTimeout))
switch messageType {
case websocket.BinaryMessage:
b.touchActivity()
writeCtx, cancel := context.WithTimeout(b.ctx, 5*time.Second)
werr := b.terminal.Session.Write(writeCtx, payload)
cancel()
if werr != nil {
logger.Debugf(b.ctx, "[sandbox-terminal] input failed session=%s: %v",
b.session, werr)
}
case websocket.TextMessage:
var frame terminalControlFrame
if json.Unmarshal(payload, &frame) != nil {
continue
}
switch frame.Type {
case "resize":
cols, rows := frame.Cols, frame.Rows
if cols <= 0 || rows <= 0 || cols > terminalMaxGeometry || rows > terminalMaxGeometry {
continue
}
b.touchActivity()
resizeCtx, cancel := context.WithTimeout(b.ctx, 5*time.Second)
rerr := b.terminal.Session.Resize(resizeCtx, uint32(cols), uint32(rows))
cancel()
if rerr != nil {
logger.Debugf(b.ctx, "[sandbox-terminal] resize failed session=%s: %v",
b.session, rerr)
}
case "ping":
b.sendControl(terminalControlFrame{Type: "pong"})
}
}
}
}
func (b *terminalBridge) touchActivity() {
b.lastActivity.Store(time.Now().UnixNano())
}
func (b *terminalBridge) lastActivityTime() time.Time {
n := b.lastActivity.Load()
if n == 0 {
return time.Time{}
}
return time.Unix(0, n)
}
// terminalIdleExpired reports whether last activity is older than idle.
// A zero last timestamp never expires so the watcher cannot fire before the
// first touchActivity in run().
func terminalIdleExpired(last time.Time, idle time.Duration, now time.Time) bool {
if idle <= 0 || last.IsZero() {
return false
}
return now.Sub(last) >= idle
}
func (b *terminalBridge) watchIdle(done <-chan struct{}) {
idle := b.idleDisconnect
if idle <= 0 {
return
}
tick := idle / 12
if tick < 200*time.Millisecond {
tick = 200 * time.Millisecond
}
if tick > 5*time.Second {
tick = 5 * time.Second
}
ticker := time.NewTicker(tick)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-b.ctx.Done():
return
case <-ticker.C:
if terminalIdleExpired(b.lastActivityTime(), idle, time.Now()) {
b.disconnectIdle()
return
}
}
}
}
func (b *terminalBridge) disconnectIdle() {
b.sendControl(terminalControlFrame{
Type: "error",
Code: terminalErrIdle,
Message: "terminal idle disconnect",
})
_ = b.conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, terminalErrIdle),
time.Now().Add(terminalWriteTimeout),
)
b.teardownWith("idle_disconnected")
}
func (b *terminalBridge) watchAuth(done <-chan struct{}) {
if b.authCheck == nil {
return
}
ticker := time.NewTicker(terminalAuthRecheckInterval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-b.ctx.Done():
return
case <-ticker.C:
checkCtx, cancel := context.WithTimeout(b.ctx, terminalAuthRecheckTimeout)
err := b.authCheck(checkCtx)
cancel()
if err == nil {
continue
}
if b.ctx.Err() != nil {
return
}
if errors.Is(err, service.ErrTerminalAuthDenied) {
b.disconnectAuth()
return
}
logger.Warnf(b.ctx, "[sandbox-terminal] auth recheck failed session=%s: %v",
b.session, err)
}
}
}
func (b *terminalBridge) disconnectAuth() {
b.sendControl(terminalControlFrame{
Type: "error",
Code: terminalErrAuth,
Message: "terminal authorization revoked",
})
_ = b.conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, terminalErrAuth),
time.Now().Add(terminalWriteTimeout),
)
b.teardownWith("auth_revoked")
}
// heartbeat pings the browser so dead TCP connections surface within
// terminalReadTimeout instead of holding PTYs open forever.
func (b *terminalBridge) heartbeat(done chan struct{}) {
ticker := time.NewTicker(terminalPingInterval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-b.ctx.Done():
return
case <-ticker.C:
// WriteControl is the only gorilla write documented as safe
// concurrently with other writers: pumpOutput streams PTY bytes
// at the same time, and two concurrent WriteMessage calls would
// corrupt the connection state (and, once c.writeErr is set,
// poison every later write — the premature-disconnect symptom).
if err := b.conn.WriteControl(
websocket.PingMessage,
nil,
time.Now().Add(terminalWriteTimeout),
); err != nil {
b.teardownWith("ping_failed")
return
}
}
}
}
// teardownLocked disconnects the PTY, closes the socket, and releases the
// session slot. Callers must go through teardownWith so the reason is logged.
func (b *terminalBridge) teardownLocked() {
b.cancel()
// On Cube/E2B Close only disconnects Academy from the PTY and the shell
// stays reattachable; Docker cannot reattach, so its Close ends the shell.
if err := b.terminal.Session.Close(); err != nil {
logger.Debugf(b.ctx, "[sandbox-terminal] close failed session=%s: %v",
b.session, err)
}
_ = b.conn.Close()
logger.Infof(b.ctx, "[sandbox-terminal] closed session=%s reason=%s",
b.session, b.teardownReason)
}
@@ -0,0 +1,173 @@
package session
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/stretchr/testify/require"
"academy/internal/application/service"
"academy/internal/sandbox"
)
// fakeTerminalSession is a RemoteTerminalSession that never produces output,
// so a test controls exactly when the bridge ends.
type fakeTerminalSession struct {
out chan sandbox.RemoteTerminalEvent
pid uint32
closes atomic.Int32
}
func newFakeTerminalSession() *fakeTerminalSession {
return &fakeTerminalSession{out: make(chan sandbox.RemoteTerminalEvent), pid: 4321}
}
func (s *fakeTerminalSession) Output() <-chan sandbox.RemoteTerminalEvent { return s.out }
func (s *fakeTerminalSession) PID() uint32 { return s.pid }
func (s *fakeTerminalSession) Write(context.Context, []byte) error { return nil }
func (s *fakeTerminalSession) Resize(context.Context, uint32, uint32) error {
return nil
}
func (s *fakeTerminalSession) Close() error {
// The real adapters make Close idempotent; mirror that and record the
// call so a test can assert the PTY was released.
if s.closes.Add(1) == 1 {
close(s.out)
}
return nil
}
// serveTerminalBridge stands up a real WebSocket endpoint driven by
// terminalBridge and dials it, so tests exercise the actual protocol rather
// than the bridge's internals.
func serveTerminalBridge(
t *testing.T,
pty *fakeTerminalSession,
authCheck func(context.Context) error,
) *websocket.Conn {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := terminalUpgrader.Upgrade(w, r, nil)
if err != nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
bridge := &terminalBridge{
conn: conn,
ctx: ctx,
cancel: cancel,
session: "sess-1",
terminal: &service.SessionTerminal{Session: pty, Backend: "fake"},
// Idle disconnect off: these tests are about the auth watcher.
idleDisconnect: 0,
authCheck: authCheck,
}
bridge.run()
}))
t.Cleanup(server.Close)
client, _, err := websocket.DefaultDialer.Dial(
"ws"+strings.TrimPrefix(server.URL, "http"), nil,
)
require.NoError(t, err)
t.Cleanup(func() { _ = client.Close() })
return client
}
func readTerminalFrame(t *testing.T, conn *websocket.Conn) terminalControlFrame {
t.Helper()
require.NoError(t, conn.SetReadDeadline(time.Now().Add(5*time.Second)))
_, payload, err := conn.ReadMessage()
require.NoError(t, err)
var frame terminalControlFrame
require.NoError(t, json.Unmarshal(payload, &frame))
return frame
}
func TestTerminalBridgeReadyAdvertisesReattachability(t *testing.T) {
for name, tc := range map[string]struct {
pid uint32
want bool
}{
"envd PTY with a pid": {pid: 4321, want: true},
"docker exec without a pid": {pid: 0, want: false},
} {
t.Run(name, func(t *testing.T) {
pty := newFakeTerminalSession()
pty.pid = tc.pid
client := serveTerminalBridge(t, pty, nil)
ready := readTerminalFrame(t, client)
require.Equal(t, "ready", ready.Type)
require.NotNil(t, ready.Reattachable,
"ready must always say whether a reconnect resumes the shell")
require.Equal(t, tc.want, *ready.Reattachable)
})
}
}
func TestTerminalBridgeTearsDownWhenAuthIsRevoked(t *testing.T) {
prev := terminalAuthRecheckInterval
terminalAuthRecheckInterval = 20 * time.Millisecond
t.Cleanup(func() { terminalAuthRecheckInterval = prev })
pty := newFakeTerminalSession()
client := serveTerminalBridge(t, pty, func(context.Context) error {
return service.ErrTerminalAuthDenied
})
require.Equal(t, "ready", readTerminalFrame(t, client).Type)
errFrame := readTerminalFrame(t, client)
require.Equal(t, "error", errFrame.Type)
require.Equal(t, terminalErrAuth, errFrame.Code)
// The socket must actually close, and the PTY must be released with it.
require.NoError(t, client.SetReadDeadline(time.Now().Add(5*time.Second)))
_, _, err := client.ReadMessage()
require.Error(t, err, "server must close the socket after revoking auth")
require.Eventually(t, func() bool {
return pty.closes.Load() > 0
}, 2*time.Second, 10*time.Millisecond, "PTY must be closed on auth teardown")
}
// The counterpart to the service-level fail-open tests: a lookup that merely
// failed must leave the terminal running so a database hiccup does not
// disconnect every open session at once.
func TestTerminalBridgeSurvivesTransientAuthLookupFailure(t *testing.T) {
prev := terminalAuthRecheckInterval
terminalAuthRecheckInterval = 10 * time.Millisecond
t.Cleanup(func() { terminalAuthRecheckInterval = prev })
var checks atomic.Int32
pty := newFakeTerminalSession()
client := serveTerminalBridge(t, pty, func(context.Context) error {
checks.Add(1)
return errors.New("db down")
})
require.Equal(t, "ready", readTerminalFrame(t, client).Type)
require.Eventually(t, func() bool {
return checks.Load() >= 3
}, 2*time.Second, 10*time.Millisecond, "watcher must keep retrying")
// Nothing further should have been sent, and the PTY is still live.
require.NoError(t, client.SetReadDeadline(time.Now().Add(150*time.Millisecond)))
_, _, err := client.ReadMessage()
require.Error(t, err)
netErr, ok := err.(interface{ Timeout() bool })
require.True(t, ok && netErr.Timeout(),
"expected a read timeout (terminal still open), got %v", err)
require.Zero(t, pty.closes.Load())
}
@@ -0,0 +1,71 @@
package session
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/require"
"academy/internal/application/service"
"academy/internal/sandbox"
)
func TestTerminalIdleExpired(t *testing.T) {
t.Parallel()
now := time.Date(2026, 9, 4, 12, 0, 0, 0, time.UTC)
last := now.Add(-15 * time.Minute)
require.False(t, terminalIdleExpired(time.Time{}, 15*time.Minute, now),
"no activity timestamp must not expire")
require.False(t, terminalIdleExpired(last, 0, now),
"zero idle must disable the watcher")
require.False(t, terminalIdleExpired(last, 20*time.Minute, now))
require.True(t, terminalIdleExpired(last, 15*time.Minute, now))
require.True(t, terminalIdleExpired(last, 10*time.Minute, now))
}
// The provision flag authorises creating a microVM from a GET, so it must be
// opt-in: absent, empty, or malformed all have to read as "do not create".
func TestTerminalFlagParam(t *testing.T) {
t.Parallel()
for _, raw := range []string{"1", "true", "TRUE", " yes ", "Yes"} {
require.True(t, terminalFlagParam(raw), "expected %q to opt in", raw)
}
for _, raw := range []string{"", " ", "0", "false", "no", "2", "on", "provision", "1;"} {
require.False(t, terminalFlagParam(raw), "expected %q to stay opted out", raw)
}
}
func TestTerminalTenantParam(t *testing.T) {
t.Parallel()
require.Equal(t, uint64(0), terminalTenantParam(""))
require.Equal(t, uint64(0), terminalTenantParam("0"))
require.Equal(t, uint64(0), terminalTenantParam("-1"))
require.Equal(t, uint64(84), terminalTenantParam("84"))
require.Equal(t, uint64(84), terminalTenantParam(" 84 "))
}
func TestTerminalAuthRecheckInterval(t *testing.T) {
t.Parallel()
require.GreaterOrEqual(t, terminalAuthRecheckInterval, time.Minute)
require.LessOrEqual(t, terminalAuthRecheckInterval, 2*time.Minute)
require.Equal(t, "AUTH_REVOKED", terminalErrAuth)
}
func TestTerminalErrorFrame(t *testing.T) {
t.Parallel()
code, _ := terminalErrorFrame(sandbox.ErrNoLiveSessionSandbox)
require.Equal(t, terminalErrNotBound, code)
code, _ = terminalErrorFrame(sandbox.ErrSandboxPaused)
require.Equal(t, terminalErrPaused, code)
code, _ = terminalErrorFrame(fmt.Errorf("open: %w", sandbox.ErrSandboxStopped))
require.Equal(t, terminalErrStopped, code,
"Docker's not-running case must not be reported as a wakeable pause")
code, _ = terminalErrorFrame(service.ErrTerminalUnsupported)
require.Equal(t, terminalErrUnsupported, code)
}
@@ -0,0 +1,448 @@
// Package session: sandbox terminal WebSocket.
//
// GET /api/v1/sessions/:session_id/sandbox/terminal?ticket=<short-lived JWT>
//
// The route is registered before the global auth middleware because a
// browser WebSocket handshake cannot carry the Authorization header. The
// browser first POSTs (with a normal Bearer token) for a 2-minute ticket
// bound to this session and to that access-token's id, then presents the
// ticket on the handshake. After upgrade the bridge rechecks the bound
// token, user, workspace membership, and session ownership about once a
// minute and tears the PTY down on failure.
//
// binary frame client→server raw keystrokes into the PTY
// binary frame server→client raw PTY output
// text frame both ways JSON control frames (resize/ping/ready/…)
package session
import (
"context"
stderrors "errors"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"academy/internal/application/service"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/middleware"
"academy/internal/sandbox"
"academy/internal/types"
)
// Terminal protocol tunables.
const (
// terminalPingInterval / terminalReadTimeout drive the liveness loop:
// the server pings, and any read (pong, keystroke, control frame)
// refreshes the read deadline. The read window is deliberately 4x the
// ping interval (not 2x) because a backgrounded browser tab throttles
// timers — its pong reply can lag well past one interval, and a tight
// window would drop terminals that are perfectly healthy.
terminalPingInterval = 30 * time.Second
terminalReadTimeout = 120 * time.Second
// terminalWriteTimeout bounds a single output-frame write so a stalled
// browser tab cannot pin the pump goroutine forever.
terminalWriteTimeout = 10 * time.Second
// terminalMaxInputBytes caps one keystroke frame; terminals exchange
// small chunks, so anything larger is abusive or buggy.
terminalMaxInputBytes = 4096
// terminalMaxGeometry caps the parsed initial geometry.
terminalMaxGeometry = 500
// terminalMaxPerSession caps concurrent PTYs per session to protect the
// sandbox from resource exhaustion.
terminalMaxPerSession = 5
terminalAuthRecheckTimeout = 10 * time.Second
)
// terminalAuthRecheckInterval is how often an open PTY re-validates the
// minting access token, user, workspace membership, and session ownership.
// Handshake auth is a snapshot; this is what closes the window after logout,
// token revocation, or being removed from the workspace. Tests lower it.
var terminalAuthRecheckInterval = time.Minute
// Protocol error codes sent as HTTP close reasons and on error frames.
const (
terminalErrNotBound = "SANDBOX_NOT_BOUND"
terminalErrPaused = "SANDBOX_PAUSED"
terminalErrStopped = "SANDBOX_STOPPED"
terminalErrUnsupported = "TERMINAL_UNSUPPORTED"
terminalErrInternal = "INTERNAL"
terminalErrIdle = "IDLE_DISCONNECTED"
terminalErrAuth = "AUTH_REVOKED"
)
// terminalUpgrader performs the WebSocket handshake.
//
// Origin is NOT checked here on purpose: authentication travels explicitly
// in the short-lived ticket query parameter and is validated before the
// upgrade, and the endpoint uses no ambient credentials (cookies), so a
// cross-origin browser tab cannot piggyback a victim session. A strict
// same-origin check would also break the dev setup, where the vite proxy
// rewrites Host to the backend address while Origin stays on the dev server.
var terminalUpgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(*http.Request) bool { return true },
}
// terminalLimiter caps concurrent PTYs per session across this process.
type terminalLimiter struct {
mu sync.Mutex
counts map[string]int
}
var sessionTerminalLimiter = &terminalLimiter{counts: make(map[string]int)}
// acquire reserves a terminal slot. The returned release func is always
// non-nil and idempotent.
func (l *terminalLimiter) acquire(sessionID string) (release func(), ok bool) {
l.mu.Lock()
defer l.mu.Unlock()
if l.counts[sessionID] >= terminalMaxPerSession {
return func() {}, false
}
l.counts[sessionID]++
released := false
return func() {
l.mu.Lock()
defer l.mu.Unlock()
if !released {
released = true
l.counts[sessionID]--
if l.counts[sessionID] <= 0 {
delete(l.counts, sessionID)
}
}
}, true
}
// terminalControlFrame is a text-mode protocol frame.
type terminalControlFrame struct {
Type string `json:"type"`
// Code carries the error code on error frames.
Code string `json:"code,omitempty"`
// Message is a human-readable detail for error frames.
Message string `json:"message,omitempty"`
// PID is the remote shell process id on ready frames.
PID uint32 `json:"pty_id,omitempty"`
// Backend names the sandbox provider on ready frames.
Backend string `json:"backend,omitempty"`
// Reattachable tells the browser, on ready frames, whether reconnecting
// with pty_id resumes this shell. False (Docker) means a reconnect gets a
// fresh shell, so the client must not redial silently.
Reattachable *bool `json:"reattachable,omitempty"`
// ExitCode is set on exited frames (-1 when the provider didn't say).
ExitCode *int `json:"exit_code,omitempty"`
// Cols/Rows carry resize requests.
Cols int `json:"cols,omitempty"`
Rows int `json:"rows,omitempty"`
}
// SandboxTerminalWS upgrades a browser connection into a session sandbox
// terminal. See the file header for the protocol.
func (h *Handler) SandboxTerminalWS(c *gin.Context) {
sessionID := strings.TrimSpace(c.Param("id"))
if sessionID == "" {
sessionID = strings.TrimSpace(c.Param("session_id"))
}
if sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})
return
}
claims, err := service.ParseSandboxTerminalTicket(c.Query("ticket"))
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid or expired ticket"})
return
}
if claims.SessionID != sessionID {
c.JSON(http.StatusForbidden, gin.H{"error": "ticket is not valid for this session"})
return
}
// One call covers the whole handshake identity: minting token still live,
// user active, workspace membership intact, session still owned. It also
// hands back the user, so nothing below re-queries it.
user, err := h.checkTerminalAuth(c.Request.Context(), *claims, true)
if err != nil {
if stderrors.Is(err, service.ErrTerminalAuthDenied) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: invalid or expired ticket"})
return
}
logger.ErrorWithFields(c.Request.Context(), err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to validate ticket"})
return
}
if !middleware.AttachAuthenticatedUser(
c, h.tenantService, h.memberService, h.config, user, claims.TenantID,
) {
return
}
ctx := c.Request.Context()
release, ok := sessionTerminalLimiter.acquire(sessionID)
if !ok {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many terminals for this session"})
return
}
defer release()
conn, err := terminalUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
// Upgrade already wrote the HTTP error response.
return
}
// Provisioning is opt-in per connect, because it creates (or resumes and
// re-bills) a microVM and this is a GET. A bare handshake — panel opened,
// tab restored, background reconnect — stays lookup-only: a running
// sandbox is attached, a paused one reports SANDBOX_PAUSED, and a
// missing one reports SANDBOX_NOT_BOUND. Only a confirmed click sets
// provision=1, which may create or resume.
allowProvision := terminalFlagParam(c.Query("provision"))
provision := h.terminalProvisionPin(ctx, c, allowProvision)
// Geometry from the query string; the frontend resizes right after
// ready anyway, so defaults only shape the first paint.
opts := sandbox.RemoteTerminalOptions{
Cols: terminalSizeParam(c.Query("cols")),
Rows: terminalSizeParam(c.Query("rows")),
AttachPID: terminalPIDParam(c.Query("pty_id")),
}
// The connection outlives the HTTP exchange, so the terminal lifetime is
// governed by this derived context, cancelled in cleanup().
termCtx, cancelTerm := context.WithCancel(context.WithoutCancel(ctx))
terminal, err := h.openTerminal(termCtx, sessionID, provision, allowProvision, opts)
if err != nil {
code, detail := terminalErrorFrame(err)
logger.Warnf(ctx, "[sandbox-terminal] open failed session=%s provision=%t code=%s: %v",
sessionID, allowProvision, code, detail)
_ = conn.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, code),
time.Now().Add(terminalWriteTimeout))
_ = conn.Close()
cancelTerm()
return
}
logger.Infof(ctx, "[sandbox-terminal] opened session=%s backend=%s pid=%d",
sessionID, terminal.Backend, terminal.Session.PID())
authClaims := *claims
bridge := &terminalBridge{
conn: conn,
ctx: termCtx,
cancel: cancelTerm,
session: sessionID,
terminal: terminal,
idleDisconnect: terminal.IdleDisconnect,
authCheck: func(checkCtx context.Context) error {
_, err := h.checkTerminalAuth(checkCtx, authClaims, false)
return err
},
}
bridge.run()
}
// openTerminal picks the lookup-only or the provisioning entry point. The
// split is the whole point of the provision flag: only a confirmed user
// action may create infrastructure.
func (h *Handler) openTerminal(
ctx context.Context,
sessionID string,
provision service.SandboxPin,
allowProvision bool,
opts sandbox.RemoteTerminalOptions,
) (*service.SessionTerminal, error) {
if allowProvision {
return h.terminalService.EnsureSessionTerminal(ctx, sessionID, provision, opts)
}
return h.terminalService.OpenSessionTerminal(ctx, sessionID, opts)
}
// terminalProvisionPin resolves the sandbox backend a confirmed create should
// use. It goes through resolveAgent so a shared agent from another workspace
// provisions the same way a chat turn would, instead of looking the agent up
// only in the current tenant.
//
// The agent's workspace travels with its config id. Sandbox configs are keyed
// by (tenant, id), so a shared agent's config simply does not exist in the
// caller's own workspace — passing the id alone resolved to "config not found"
// and the panel died with a bare INTERNAL frame.
func (h *Handler) terminalProvisionPin(
ctx context.Context, c *gin.Context, allowProvision bool,
) service.SandboxPin {
if !allowProvision || h == nil || c == nil {
return service.SandboxPin{}
}
agentID := strings.TrimSpace(c.Query("agent_id"))
if agentID == "" {
return service.SandboxPin{}
}
agent, agentTenantID, _ := h.resolveAgent(
ctx, c, agentID, terminalTenantParam(c.Query("agent_source_tenant_id")))
if agent == nil {
return service.SandboxPin{}
}
// resolveAgent reports 0 for the caller's own agent, which is exactly the
// "use the request workspace" fallback SandboxPin.TenantOr applies.
return service.SandboxPin{
ConfigID: strings.TrimSpace(agent.Config.SandboxConfigID),
TenantID: agentTenantID,
}
}
func terminalTenantParam(raw string) uint64 {
value, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 64)
if err != nil || value == 0 {
return 0
}
return value
}
// terminalFlagParam parses an opt-in query flag. Anything other than an
// explicit truthy value is false, so a missing or malformed parameter can
// never authorise a side effect.
func terminalFlagParam(raw string) bool {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "1", "true", "yes":
return true
default:
return false
}
}
// terminalSizeParam parses a non-negative geometry query parameter.
func terminalSizeParam(raw string) uint32 {
value, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 32)
if err != nil || value <= 0 || value > terminalMaxGeometry {
return 0
}
return uint32(value)
}
func terminalPIDParam(raw string) uint32 {
value, err := strconv.ParseUint(strings.TrimSpace(raw), 10, 32)
if err != nil || value == 0 {
return 0
}
return uint32(value)
}
// IssueSandboxTerminalTicket mints a short-lived handshake ticket for the
// WebSocket. The access JWT stays on this authenticated POST and never
// appears in the WS URL (or nginx access logs of that handshake).
func (h *Handler) IssueSandboxTerminalTicket(c *gin.Context) {
ctx := c.Request.Context()
sessionID := strings.TrimSpace(c.Param("session_id"))
if sessionID == "" {
sessionID = strings.TrimSpace(c.Param("id"))
}
if sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})
return
}
if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
}
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load session"})
return
}
userID, ok := types.UserIDFromContext(ctx)
if !ok || userID == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok || tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
accessToken := sandboxTerminalBearerToken(c)
if accessToken == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: access token required"})
return
}
record, err := h.userService.GetAccessTokenByValue(ctx, accessToken)
if err != nil || record == nil || strings.TrimSpace(record.ID) == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
if err := service.AssertAccessTokenStillActive(record, userID, time.Now()); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
ticket, err := service.IssueSandboxTerminalTicket(userID, tenantID, sessionID, record.ID, 0)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to issue ticket"})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"ticket": ticket,
"expires_in": int(service.DefaultSandboxTerminalTicketTTL.Seconds()),
},
})
}
// terminalErrorFrame maps an OpenSessionTerminal failure onto a protocol
// error code and a short message.
func terminalErrorFrame(err error) (code, message string) {
switch {
case stderrors.Is(err, sandbox.ErrNoLiveSessionSandbox):
return terminalErrNotBound, "session has no live sandbox"
// Before ErrSandboxPaused, which it wraps.
case stderrors.Is(err, sandbox.ErrSandboxStopped):
return terminalErrStopped, "session sandbox is stopped or was reclaimed"
case stderrors.Is(err, sandbox.ErrSandboxPaused):
return terminalErrPaused, "session sandbox is paused"
case stderrors.Is(err, service.ErrTerminalUnsupported):
return terminalErrUnsupported, "sandbox backend does not support terminals"
default:
return terminalErrInternal, "failed to open terminal"
}
}
func sandboxTerminalBearerToken(c *gin.Context) string {
header := strings.TrimSpace(c.GetHeader("Authorization"))
if !strings.HasPrefix(header, "Bearer ") {
return ""
}
return strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
}
func (h *Handler) checkTerminalAuth(
ctx context.Context,
claims service.SandboxTerminalTicketClaims,
rejectExpired bool,
) (*types.User, error) {
if h == nil {
return nil, service.ErrTerminalAuthDenied
}
return service.CheckSandboxTerminalAuth(
ctx,
h.userService,
h.memberService,
h.sessionService,
claims,
h.terminalRBACEnforced(),
rejectExpired,
)
}
func (h *Handler) terminalRBACEnforced() bool {
return h != nil && h.config != nil && h.config.Tenant.IsRBACEnforced()
}
@@ -0,0 +1,175 @@
package session
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
type stubSearchSessionService struct {
interfaces.SessionService
calls int
lastOpts *types.KnowledgeSearchOptions
}
func (s *stubSearchSessionService) SearchKnowledge(
_ context.Context, _ []string, _ []string, _ []types.TagScope, _ string, opts *types.KnowledgeSearchOptions,
) (*types.RetrievalResult, error) {
s.calls++
s.lastOpts = opts
return &types.RetrievalResult{
Results: []*types.SearchResult{{
Content: "chunk ![c](" + testResourceHandle + ")",
ImageInfo: `[{"url":"` + testResourceHandle + `"}]`,
}},
Meta: types.RetrievalMeta{Rerank: &types.RerankDiagnostics{
Applied: true, Outcome: types.RerankOutcomeOK, ModelID: "rr-1", ModelSource: types.RerankModelSourceTenant,
}},
}, nil
}
func TestSearchKnowledge_PublicResourceURLs(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{
sessionService: &stubSearchSessionService{},
fileService: &stubResourceFileService{},
}
r.POST("/knowledge-search", h.SearchKnowledge)
body := bytes.NewBufferString(`{"query":"diagram","knowledge_base_ids":["kb-1"]}`)
req := httptest.NewRequest(http.MethodPost, "/knowledge-search?resource_urls=public", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
assert.NotContains(t, w.Body.String(), testResourceHandle)
assert.Contains(t, w.Body.String(), "cdn.example.com")
}
func TestSearchKnowledge_InvalidResourceURLMode(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{
sessionService: &stubSearchSessionService{},
fileService: &stubResourceFileService{},
}
r.POST("/knowledge-search", h.SearchKnowledge)
body := bytes.NewBufferString(`{"query":"diagram","knowledge_base_ids":["kb-1"]}`)
req := httptest.NewRequest(http.MethodPost, "/knowledge-search?resource_urls=signed", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code, "body=%s", w.Body.String())
assert.Contains(t, w.Body.String(), "resource_urls")
}
func TestSearchKnowledge_DefaultKeepsHandles(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{
sessionService: &stubSearchSessionService{},
fileService: &stubResourceFileService{},
}
r.POST("/knowledge-search", h.SearchKnowledge)
body := bytes.NewBufferString(`{"query":"diagram","knowledge_base_ids":["kb-1"]}`)
req := httptest.NewRequest(http.MethodPost, "/knowledge-search", body)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
var resp struct {
Data []struct {
Content string `json:"content"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp))
require.Len(t, resp.Data, 1)
assert.Contains(t, resp.Data[0].Content, testResourceHandle)
}
func performKnowledgeSearch(t *testing.T, svc *stubSearchSessionService, body string) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &Handler{sessionService: svc, fileService: &stubResourceFileService{}}
r.POST("/knowledge-search", h.SearchKnowledge)
req := httptest.NewRequest(http.MethodPost, "/knowledge-search", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestSearchKnowledge_PassesRetrievalOverridesAndReturnsMeta(t *testing.T) {
svc := &stubSearchSessionService{}
w := performKnowledgeSearch(t, svc, `{
"query":"q","knowledge_base_ids":["kb-1"],
"vector_threshold":0.4,"keyword_threshold":0,"match_count":7,"disable_keywords_match":true,
"rerank":{"enabled":false}
}`)
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
opts := svc.lastOpts
require.NotNil(t, opts)
require.NotNil(t, opts.VectorThreshold)
require.NotNil(t, opts.KeywordThreshold, "an explicit 0 must survive as an override")
assert.Equal(t, 0.4, *opts.VectorThreshold)
assert.Equal(t, 0.0, *opts.KeywordThreshold)
assert.Equal(t, 7, opts.MatchCount)
assert.True(t, opts.DisableKeywordsMatch)
require.NotNil(t, opts.Rerank)
assert.False(t, opts.Rerank.IsEnabled())
var body struct {
Meta types.RetrievalMeta `json:"meta"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.NotNil(t, body.Meta.Rerank)
assert.Equal(t, types.RerankOutcomeOK, body.Meta.Rerank.Outcome)
assert.Equal(t, types.RerankModelSourceTenant, body.Meta.Rerank.ModelSource)
}
func TestSearchKnowledge_OmittedOverridesKeepTenantConfig(t *testing.T) {
svc := &stubSearchSessionService{}
w := performKnowledgeSearch(t, svc, `{"query":"q","knowledge_base_ids":["kb-1"]}`)
require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String())
require.NotNil(t, svc.lastOpts)
assert.Equal(t, types.KnowledgeSearchOptions{}, *svc.lastOpts)
}
func TestSearchKnowledge_RejectsInvalidOverrides(t *testing.T) {
for name, extra := range map[string]string{
"negative match_count": `"match_count":-1`,
"both recall paths off": `"disable_keywords_match":true,"disable_vector_match":true`,
"negative rerank top_k": `"rerank":{"top_k":-2}`,
} {
t.Run(name, func(t *testing.T) {
svc := &stubSearchSessionService{}
w := performKnowledgeSearch(t, svc, `{"query":"q","knowledge_base_ids":["kb-1"],`+extra+`}`)
require.Equal(t, http.StatusBadRequest, w.Code, "body=%s", w.Body.String())
assert.Zero(t, svc.calls)
})
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,391 @@
package session
import (
"context"
"errors"
"testing"
"academy/internal/stream"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseSteerDelivery(t *testing.T) {
t.Parallel()
cases := []struct {
in string
want string
wantErr bool
}{
// Omitted delivery must queue, not interrupt: a client that does not
// know about the field should never land inside a running turn.
{"", steerDeliveryAfter, false},
{"inject", steerDeliveryInject, false},
{"INJECT", steerDeliveryInject, false},
{"after", steerDeliveryAfter, false},
{"After", steerDeliveryAfter, false},
{"queue", "", true},
{"now", "", true},
{"bogus", "", true},
}
for _, tc := range cases {
got, err := parseSteerDelivery(tc.in)
if tc.wantErr {
assert.Error(t, err, "in=%q", tc.in)
continue
}
require.NoError(t, err, "in=%q", tc.in)
assert.Equal(t, tc.want, got, "in=%q", tc.in)
}
}
func TestSelectSteerBacklogKeepsAfterAndUndrainedInject(t *testing.T) {
t.Parallel()
events := []interfaces.StreamEvent{
steerEvent("a", "inject-a", nil, "web"),
steerEventWithDelivery("b", "after-b", steerDeliveryAfter),
steerEvent("c", "inject-c", nil, "web"),
steerEventWithDelivery("d", "after-d", steerDeliveryAfter),
steerEvent("e", "inject-e", nil, "web"),
}
backlog := selectSteerBacklog(events, map[string]struct{}{"a": {}, "c": {}})
require.Len(t, backlog, 3)
assert.Equal(t, "b", backlog[0].ID)
assert.Equal(t, "d", backlog[1].ID)
assert.Equal(t, "e", backlog[2].ID)
}
func TestSelectSteerBacklogNothingWhenAllInjectDrainedAndNoAfter(t *testing.T) {
t.Parallel()
events := []interfaces.StreamEvent{
steerEvent("a", "inject-a", nil, "web"),
steerEvent("b", "inject-b", nil, "web"),
}
assert.Empty(t, selectSteerBacklog(events, map[string]struct{}{"a": {}, "b": {}}))
}
func TestSelectSteerBacklogAllWhenNeverDrained(t *testing.T) {
t.Parallel()
events := []interfaces.StreamEvent{
steerEvent("a", "inject-a", nil, "web"),
steerEventWithDelivery("b", "after-b", steerDeliveryAfter),
}
backlog := selectSteerBacklog(events, nil)
require.Len(t, backlog, 2)
assert.Equal(t, "a", backlog[0].ID)
assert.Equal(t, "b", backlog[1].ID)
}
func TestSelectSteerBacklogKeepsPromotedAfterUntilInjected(t *testing.T) {
t.Parallel()
events := []interfaces.StreamEvent{
steerEventWithDelivery("b", "after-b", steerDeliveryInject),
}
backlog := selectSteerBacklog(events, map[string]struct{}{})
require.Len(t, backlog, 1)
assert.Equal(t, "b", backlog[0].ID)
assert.Empty(t, selectSteerBacklog(events, map[string]struct{}{"b": {}}))
}
func TestPollSteerSkipsAfterDeliveryAndAdvancesOffset(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEvent("a", "inject-a", nil, "web"),
steerEventWithDelivery("b", "after-b", steerDeliveryAfter),
steerEvent("c", "inject-c", nil, "web"),
}))
sink := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, &steerPersistingMessageStub{}, mgr)
events, next, err := sink.PollSteer(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, events, 2)
assert.Equal(t, "a", events[0]["id"])
assert.Equal(t, "c", events[1]["id"])
assert.Equal(t, 3, next)
assert.Equal(t, 3, sink.DrainedOffset())
repolled, _, err := sink.PollSteer(ctx, "sess", "assist", next)
require.NoError(t, err)
assert.Equal(t, events, repolled, "polling must leave unpersisted items available for retry")
assert.Empty(t, sink.InjectedIDs(), "polling alone must not hide items from follow-up handoff")
for _, evt := range events {
require.NotEmpty(t, sink.PersistSteerMessage(ctx, "sess", "assist",
getString(evt, "id"), getString(evt, "content"), nil, "web"))
}
assert.Len(t, sink.InjectedIDs(), len(events))
events, next, err = sink.PollSteer(ctx, "sess", "assist", next)
require.NoError(t, err)
assert.Empty(t, events)
assert.Equal(t, 3, next)
}
func TestPollSteerPicksUpAfterPromotedToInject(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("b", "wait-then-nudge", steerDeliveryAfter),
}))
sink := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, nil, mgr)
events, _, err := sink.PollSteer(ctx, "sess", "assist", 0)
require.NoError(t, err)
assert.Empty(t, events)
ok, err := promoteSteerForTest(ctx, mgr, "b")
require.NoError(t, err)
assert.True(t, ok)
events, _, err = sink.PollSteer(ctx, "sess", "assist", sink.DrainedOffset())
require.NoError(t, err)
require.Len(t, events, 1)
assert.Equal(t, "b", events[0]["id"])
assert.Equal(t, "wait-then-nudge", events[0]["content"])
}
func TestSetSteerDeliveryUpdatesExistingAfterEvent(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("keep", "later", steerDeliveryAfter),
steerEventWithDelivery("flip", "now", steerDeliveryAfter),
}))
ok, err := promoteSteerForTest(ctx, mgr, "flip")
require.NoError(t, err)
assert.True(t, ok)
events, _, err := mgr.GetSteerEvents(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, events, 2)
assert.Equal(t, steerDeliveryAfter, events[0].Data["delivery"])
assert.Equal(t, steerDeliveryInject, events[1].Data["delivery"])
ok, err = promoteSteerForTest(ctx, mgr, "missing")
require.NoError(t, err)
assert.False(t, ok)
}
// TestPollSteerMarksConsumedDurably pins the cross-replica contract: once the
// engine has taken a message, the flag lives on the event itself. Anything
// that reads the queue afterwards — the overlay, the depth guard, a follow-up
// handoff running in another process — must see it as gone.
func TestPollSteerMarksConsumedDurably(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("a", "do it now", steerDeliveryInject),
steerEventWithDelivery("b", "and later this", steerDeliveryAfter),
}))
msgs := &steerPersistingMessageStub{}
sink := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, msgs, mgr)
events, _, err := sink.PollSteer(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, events, 1)
require.NotEmpty(t, sink.PersistSteerMessage(ctx, "sess", "assist", "a", "do it now", nil, "web"))
stored, _, err := mgr.GetSteerEvents(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, stored, 2)
assert.True(t, steerEventConsumed(stored[0]), "injected event must be flagged consumed")
assert.False(t, steerEventConsumed(stored[1]), "queued after-event must stay pending")
// A fresh sink stands in for another replica: it must not replay the
// message the first one already handed to the model.
other := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, nil, mgr)
replayed, _, err := other.PollSteer(ctx, "sess", "assist", 0)
require.NoError(t, err)
assert.Empty(t, replayed)
// And it is no longer part of the backlog handed to a follow-up run.
assert.Len(t, selectSteerBacklog(stored, nil), 1)
}
// TestPollSteerDoesNotMutateAlreadyReadEvents guards the copy-on-write in the
// memory manager: marking consumed must not retroactively edit event copies
// the teardown path already captured for carry-over.
func TestPollSteerDoesNotMutateAlreadyReadEvents(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("a", "carry me over", steerDeliveryAfter),
}))
captured, _, err := mgr.GetSteerEvents(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, captured, 1)
ok, err := mgr.UpdateSteerEventData(ctx, "sess", "assist", "a",
map[string]interface{}{steerDataConsumed: true})
require.NoError(t, err)
require.True(t, ok)
assert.False(t, steerEventConsumed(captured[0]),
"carry-over copy must stay pending so the follow-up run can inject it")
}
// promoteSteerForTest is the "立即发送" mutation the handler performs.
func promoteSteerForTest(
ctx context.Context, mgr *stream.MemoryStreamManager, steerID string,
) (bool, error) {
return mgr.UpdateSteerEventData(ctx, "sess", "assist", steerID,
map[string]interface{}{"delivery": steerDeliveryInject})
}
func TestDeleteSteerEventRemovesPendingAfter(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("keep", "later", steerDeliveryAfter),
steerEventWithDelivery("drop", "gone", steerDeliveryAfter),
}))
ok, err := mgr.DeleteSteerEvent(ctx, "sess", "assist", "drop")
require.NoError(t, err)
assert.True(t, ok)
events, _, err := mgr.GetSteerEvents(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, events, 1)
assert.Equal(t, "keep", events[0].ID)
ok, err = mgr.DeleteSteerEvent(ctx, "sess", "assist", "drop")
require.NoError(t, err)
assert.False(t, ok)
}
func TestSteerEventCarriesDelivery(t *testing.T) {
t.Parallel()
evt := steerEventWithDelivery("id-1", "hello", steerDeliveryAfter)
assert.Equal(t, types.ResponseTypeSteer, evt.Type)
assert.Equal(t, steerDeliveryAfter, evt.Data["delivery"])
assert.Equal(t, "hello", evt.Content)
}
func TestPendingSteerQueueItemsOmitsInjectedKeepsAfter(t *testing.T) {
t.Parallel()
events := []interfaces.StreamEvent{
steerEvent("a", "inject-done", nil, "web"),
steerEventWithDelivery("b", "first after", steerDeliveryAfter),
steerEventWithDelivery("c", "second after", steerDeliveryAfter),
}
items := pendingSteerQueueItems(events, map[string]struct{}{"a": {}})
require.Len(t, items, 2)
assert.Equal(t, "b", items[0]["steer_id"])
assert.Equal(t, "first after", items[0]["content"])
assert.Equal(t, steerDeliveryAfter, items[0]["delivery"])
assert.Equal(t, "c", items[1]["steer_id"])
assert.Equal(t, steerDeliveryAfter, items[1]["delivery"])
}
func TestPendingSteerQueueItemsOmitsConsumedWithoutInMemoryState(t *testing.T) {
t.Parallel()
consumed := steerEventWithDelivery("a", "already injected", steerDeliveryInject)
consumed.Data[steerDataConsumed] = true
events := []interfaces.StreamEvent{
consumed,
steerEventWithDelivery("b", "still waiting", steerDeliveryAfter),
}
// nil injectedIDs stands in for a replica that never ran this turn: the
// durable flag alone has to keep the overlay honest after a refresh.
items := pendingSteerQueueItems(events, nil)
require.Len(t, items, 1)
assert.Equal(t, "b", items[0]["steer_id"])
}
func steerEventWithDelivery(id, query, delivery string) interfaces.StreamEvent {
evt := steerEvent(id, query, nil, "web")
evt.Data["delivery"] = delivery
return evt
}
type steerUpdateFailingManager struct {
interfaces.StreamManager
}
func (s *steerUpdateFailingManager) UpdateSteerEventData(
context.Context, string, string, string, map[string]interface{},
) (bool, error) {
return false, errors.New("cas exhausted")
}
func TestPersistSteerMessageRollsBackRowWhenConsumeFails(t *testing.T) {
inner := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, inner.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("a", "do it now", steerDeliveryInject),
}))
msgs := &steerPersistingMessageStub{}
sink := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, msgs,
&steerUpdateFailingManager{StreamManager: inner})
assert.Empty(t, sink.PersistSteerMessage(ctx, "sess", "assist", "a", "do it now", nil, "web"))
assert.Empty(t, msgs.byID, "failed consume must delete the user row so a retry cannot duplicate it")
}
func TestPersistSteerMessageDropsAfterRepeatedInsertFailures(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("a", "unwritable", steerDeliveryInject),
steerEventWithDelivery("b", "next", steerDeliveryInject),
}))
sink := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, &steerFailingCreateStub{}, mgr)
for i := 1; i < maxSteerPersistAttempts; i++ {
require.Empty(t, sink.PersistSteerMessage(ctx, "sess", "assist", "a", "unwritable", nil, "web"))
events, _, err := sink.PollSteer(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, events, 2, "a failure below the bound keeps the event at the head of the queue")
}
require.Empty(t, sink.PersistSteerMessage(ctx, "sess", "assist", "a", "unwritable", nil, "web"))
events, _, err := sink.PollSteer(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, events, 1)
assert.Equal(t, "b", events[0]["id"], "later messages proceed once the head is retired")
all, _, err := mgr.GetSteerEvents(ctx, "sess", "assist", 0)
require.NoError(t, err)
assert.True(t, steerEventConsumed(all[0]))
assert.Equal(t, true, all[0].Data[steerDataDropped])
backlog := selectSteerBacklog(all, sink.InjectedIDs())
require.Len(t, backlog, 1, "a dropped event must not become the follow-up query")
assert.Equal(t, "b", backlog[0].ID)
}
func TestPersistSteerMessageIsIdempotentAfterConsume(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{
steerEventWithDelivery("a", "do it now", steerDeliveryInject),
}))
msgs := &steerPersistingMessageStub{}
sink := newSteerSink(ctx, "sess", "req", &types.Message{ID: "assist"}, msgs, mgr)
first := sink.PersistSteerMessage(ctx, "sess", "assist", "a", "do it now", nil, "api")
require.NotEmpty(t, first)
second := sink.PersistSteerMessage(ctx, "sess", "assist", "a", "do it now", nil, "api")
assert.Equal(t, first, second)
assert.Equal(t, 1, msgs.n)
assert.Equal(t, "api", msgs.byID[first].Channel)
}
func TestDeleteConsumedSteerEventIsNoOp(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
evt := steerEventWithDelivery("a", "already in the model", steerDeliveryInject)
evt.Data[steerDataConsumed] = true
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess", "assist", []interfaces.StreamEvent{evt}))
ok, err := mgr.DeleteSteerEvent(ctx, "sess", "assist", "a")
require.NoError(t, err)
assert.False(t, ok)
stored, _, err := mgr.GetSteerEvents(ctx, "sess", "assist", 0)
require.NoError(t, err)
require.Len(t, stored, 1)
assert.Equal(t, "a", stored[0].ID)
}
@@ -0,0 +1,515 @@
package session
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/middleware"
"academy/internal/stream"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// A Redis/DB blip on the live-run lookup used to collapse into "no run is
// live". SteerMessage then answered status=new_run, and the client started a
// second AgentQA on top of the still-generating one. These tests pin the
// contract: lookup failure is retryable (503); only a genuine empty or
// completed marker may say new_run.
type steerOwnedSessionStub struct {
interfaces.SessionService
}
func (s *steerOwnedSessionStub) GetOwnedSession(_ context.Context, id string) (*types.Session, error) {
return &types.Session{ID: id}, nil
}
type steerMessageLookupStub struct {
interfaces.MessageService
msg *types.Message
err error
}
func (s *steerMessageLookupStub) GetMessage(_ context.Context, _, _ string) (*types.Message, error) {
return s.msg, s.err
}
type steerLiveRunLookupStub struct {
interfaces.StreamManager
assistantID string
err error
cleared string
}
func (s *steerLiveRunLookupStub) GetLiveRun(context.Context, string) (string, string, error) {
return s.assistantID, "req-1", s.err
}
func (s *steerLiveRunLookupStub) ClearLiveRun(_ context.Context, _, assistantID string) error {
s.cleared = assistantID
return nil
}
func newSteerLiveRunRouter(h *Handler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.POST("/sessions/:session_id/steer", h.SteerMessage)
r.POST("/sessions/:session_id/steer/:steer_id/inject", h.PromoteSteerMessage)
r.GET("/sessions/:id/steer", h.ListSteerMessages)
r.DELETE("/sessions/:id/steer/:steer_id", h.DeleteSteerMessage)
return r
}
func postSteer(t *testing.T, r *gin.Engine, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/sessions/sess-1/steer", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestSteerMessageLiveRunLookupFailureReturns503(t *testing.T) {
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{},
streamManager: &steerLiveRunLookupStub{err: errors.New("redis timeout")},
}
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"nudge the agent"}`)
require.Equal(t, http.StatusServiceUnavailable, w.Code, w.Body.String())
assert.NotContains(t, w.Body.String(), `"new_run"`)
}
func TestSteerMessageMessageLookupFailureReturns503(t *testing.T) {
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{err: errors.New("db timeout")},
streamManager: &steerLiveRunLookupStub{assistantID: "assist-1"},
}
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"nudge the agent"}`)
require.Equal(t, http.StatusServiceUnavailable, w.Code, w.Body.String())
assert.NotContains(t, w.Body.String(), `"new_run"`)
}
func TestSteerMessageNoLiveRunStillReturnsNewRun(t *testing.T) {
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{},
streamManager: &steerLiveRunLookupStub{},
}
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"hello"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var body map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
assert.Equal(t, "new_run", body["status"])
}
func TestSteerMessageCompletedLiveRunStillReturnsNewRun(t *testing.T) {
streams := &steerLiveRunLookupStub{assistantID: "assist-1"}
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{
msg: &types.Message{ID: "assist-1", IsCompleted: true},
},
streamManager: streams,
}
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"hello"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var body map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
assert.Equal(t, "new_run", body["status"])
assert.Equal(t, "assist-1", streams.cleared)
}
func TestSteerMessageQueuesWhenLiveRunIsVerified(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(t.Context(), "sess-1", "assist-1", "req-1"))
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{
msg: &types.Message{ID: "assist-1", SessionID: "sess-1", IsCompleted: false},
},
streamManager: mgr,
}
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"keep going","delivery":"after"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var body map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
assert.Equal(t, "queued", body["status"])
assert.Equal(t, "assist-1", body["assistant_message_id"])
}
func TestSteerMessageStripsNUL(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(t.Context(), "sess-1", "assist-1", "req-1"))
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{
msg: &types.Message{ID: "assist-1", SessionID: "sess-1", IsCompleted: false},
},
streamManager: mgr,
}
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"keep\u0000 going","delivery":"inject"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
events, _, err := mgr.GetSteerEvents(t.Context(), "sess-1", "assist-1", 0)
require.NoError(t, err)
require.Len(t, events, 1)
assert.Equal(t, "keep going", events[0].Content)
w = postSteer(t, newSteerLiveRunRouter(h), `{"query":"\u0000","delivery":"inject"}`)
assert.Equal(t, http.StatusBadRequest, w.Code, "a NUL-only query is empty")
}
func TestPromoteAndListLiveRunLookupFailureReturns503(t *testing.T) {
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{},
streamManager: &steerLiveRunLookupStub{err: errors.New("redis timeout")},
}
r := newSteerLiveRunRouter(h)
promote := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/sessions/sess-1/steer/s1/inject", bytes.NewBufferString(`{}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(promote, req)
require.Equal(t, http.StatusServiceUnavailable, promote.Code, promote.Body.String())
assert.NotContains(t, promote.Body.String(), `"new_run"`)
list := httptest.NewRecorder()
r.ServeHTTP(list, httptest.NewRequest(http.MethodGet, "/sessions/sess-1/steer", nil))
require.Equal(t, http.StatusServiceUnavailable, list.Code, list.Body.String())
assert.NotContains(t, list.Body.String(), `"items"`)
del := httptest.NewRecorder()
r.ServeHTTP(del, httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/steer/s1", nil))
require.Equal(t, http.StatusServiceUnavailable, del.Code, del.Body.String())
assert.NotContains(t, del.Body.String(), `"gone"`)
}
// steerPersistingMessageStub assigns IDs on create so a follow-up can claim
// the live-run marker without a database.
type steerPersistingMessageStub struct {
interfaces.MessageService
n int
byID map[string]*types.Message
}
func (s *steerPersistingMessageStub) CreateMessage(_ context.Context, msg *types.Message) (*types.Message, error) {
s.n++
out := *msg
if out.ID == "" {
out.ID = fmt.Sprintf("msg-%d", s.n)
}
if s.byID == nil {
s.byID = map[string]*types.Message{}
}
stored := out
s.byID[out.ID] = &stored
return &out, nil
}
func (s *steerPersistingMessageStub) DeleteMessage(_ context.Context, _, id string) error {
if s.byID != nil {
delete(s.byID, id)
}
return nil
}
func (s *steerPersistingMessageStub) GetMessage(_ context.Context, _, id string) (*types.Message, error) {
if s.byID == nil {
return nil, errors.New("not found")
}
msg, ok := s.byID[id]
if !ok {
return nil, errors.New("not found")
}
cloned := *msg
return &cloned, nil
}
// The previous run's ClearLiveRun used to run before the follow-up had an
// assistant row or a live marker. POST /steer then answered new_run and the
// client started a second AgentQA alongside kick's executeQA. Claiming the
// session (persist + SetLiveRun) must finish before that Clear, and the CAS
// Clear of the old id must leave the new marker in place.
func TestSteerFollowUpHandoffKeepsSessionLiveAcrossPreviousClear(t *testing.T) {
ctx := t.Context()
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(ctx, "sess-1", "assist-A", "req-A"))
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess-1", "assist-A", []interfaces.StreamEvent{
steerEventWithDelivery("after-1", "do this next", steerDeliveryAfter),
steerEventWithDelivery("after-2", "then this", steerDeliveryAfter),
}))
msgs := &steerPersistingMessageStub{}
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: msgs,
streamManager: mgr,
}
prev := &qaRequestContext{
sessionID: "sess-1",
session: &types.Session{ID: "sess-1"},
resume: &types.AgentResume{Snapshot: []byte(`{"version":1}`)},
}
streamCtx := &sseStreamContext{assistantMessage: &types.Message{ID: "assist-A"}}
followUp, ok := h.claimNextSteerFollowUp(ctx, prev, streamCtx)
require.True(t, ok)
require.NotNil(t, followUp)
require.Nil(t, followUp.buildQARequest().Resume)
assert.Equal(t, "do this next", followUp.query)
assert.Equal(t, "do this next", msgs.byID[followUp.userMessageID].Content)
require.NotEmpty(t, followUp.assistantMessage.ID)
assert.NotEqual(t, "assist-A", followUp.assistantMessage.ID)
assert.Empty(t, followUp.steerCarryOver, "carry-over must already sit on the new run's list")
liveID, liveReq, err := mgr.GetLiveRun(ctx, "sess-1")
require.NoError(t, err)
assert.Equal(t, followUp.assistantMessage.ID, liveID)
assert.Equal(t, followUp.requestID, liveReq)
require.NoError(t, mgr.ClearLiveRun(ctx, "sess-1", "assist-A"))
liveID, _, err = mgr.GetLiveRun(ctx, "sess-1")
require.NoError(t, err)
assert.Equal(t, followUp.assistantMessage.ID, liveID,
"ClearLiveRun of the finished run must not drop the follow-up marker")
events, _, err := mgr.GetSteerEvents(ctx, "sess-1", followUp.assistantMessage.ID, 0)
require.NoError(t, err)
require.Len(t, events, 1)
assert.Equal(t, "after-2", events[0].ID)
old, _, err := mgr.GetSteerEvents(ctx, "sess-1", "assist-A", 0)
require.NoError(t, err)
require.Len(t, old, 2)
assert.True(t, steerEventConsumed(old[0]))
assert.True(t, steerEventConsumed(old[1]))
w := postSteer(t, newSteerLiveRunRouter(h), `{"query":"and this too","delivery":"after"}`)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
var body map[string]interface{}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
assert.Equal(t, "queued", body["status"],
"a send during handoff must queue on the follow-up, not start a third run")
assert.Equal(t, followUp.assistantMessage.ID, body["assistant_message_id"])
}
func TestClaimNextSteerFollowUpNoBacklogLeavesMarkerUntouched(t *testing.T) {
ctx := t.Context()
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(ctx, "sess-1", "assist-A", "req-A"))
h := &Handler{streamManager: mgr}
followUp, ok := h.claimNextSteerFollowUp(ctx, &qaRequestContext{sessionID: "sess-1"},
&sseStreamContext{assistantMessage: &types.Message{ID: "assist-A"}})
assert.False(t, ok)
assert.Nil(t, followUp)
liveID, _, err := mgr.GetLiveRun(ctx, "sess-1")
require.NoError(t, err)
assert.Equal(t, "assist-A", liveID)
}
func TestClaimNextSteerFollowUpPersistFailureLeavesBacklog(t *testing.T) {
ctx := t.Context()
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(ctx, "sess-1", "assist-A", "req-A"))
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess-1", "assist-A", []interfaces.StreamEvent{
steerEventWithDelivery("after-1", "do this next", steerDeliveryAfter),
}))
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerFailingCreateStub{},
streamManager: mgr,
}
followUp, ok := h.claimNextSteerFollowUp(ctx, &qaRequestContext{sessionID: "sess-1"},
&sseStreamContext{assistantMessage: &types.Message{ID: "assist-A"}})
assert.False(t, ok)
assert.Nil(t, followUp)
old, _, err := mgr.GetSteerEvents(ctx, "sess-1", "assist-A", 0)
require.NoError(t, err)
require.Len(t, old, 1)
assert.False(t, steerEventConsumed(old[0]))
}
func TestRebindSteerMovesEventOntoNewLiveRun(t *testing.T) {
ctx := t.Context()
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.SetLiveRun(ctx, "sess-1", "assist-A", "req-A"))
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{
msg: &types.Message{ID: "assist-B", SessionID: "sess-1", IsCompleted: false},
},
streamManager: mgr,
}
evt := steerEventWithDelivery("late-1", "landed on A", steerDeliveryAfter)
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess-1", "assist-A", []interfaces.StreamEvent{evt}))
require.NoError(t, mgr.ClaimLiveRun(ctx, "sess-1", "assist-B", "req-B"))
queuedOn, status, err := h.rebindSteerIfLiveRunMoved(ctx, "sess-1", "assist-A", evt)
require.NoError(t, err)
assert.Equal(t, "queued", status)
assert.Equal(t, "assist-B", queuedOn)
old, _, err := mgr.GetSteerEvents(ctx, "sess-1", "assist-A", 0)
require.NoError(t, err)
assert.Empty(t, old)
moved, _, err := mgr.GetSteerEvents(ctx, "sess-1", "assist-B", 0)
require.NoError(t, err)
require.Len(t, moved, 1)
assert.Equal(t, "late-1", moved[0].ID)
}
func TestApplyFollowUpMentionsMergesKBAndMCP(t *testing.T) {
h := &Handler{}
followUp := &qaRequestContext{
knowledgeBaseIDs: []string{"kb-old"},
mcpServiceIDs: []string{"mcp-old"},
}
h.applyFollowUpMentions(t.Context(), followUp, []interface{}{
map[string]interface{}{"id": "kb-new", "type": "kb", "name": "New KB"},
map[string]interface{}{"id": "mcp-new", "type": "mcp", "name": "MCP"},
})
assert.Equal(t, []string{"kb-old", "kb-new"}, followUp.knowledgeBaseIDs)
assert.Equal(t, []string{"mcp-old", "mcp-new"}, followUp.mcpServiceIDs)
}
type steerFailingCreateStub struct {
interfaces.MessageService
}
func (s *steerFailingCreateStub) CreateMessage(context.Context, *types.Message) (*types.Message, error) {
return nil, errors.New("db down")
}
func TestPersistTurnMessagesSkipsWhenAlreadyClaimed(t *testing.T) {
msgs := &steerPersistingMessageStub{}
h := &Handler{messageService: msgs}
reqCtx := &qaRequestContext{
sessionID: "sess-1",
query: "already persisted",
requestID: "req-B",
userMessageID: "user-1",
assistantMessage: &types.Message{
ID: "assist-B",
SessionID: "sess-1",
Role: "assistant",
},
}
require.NoError(t, h.persistTurnMessages(t.Context(), reqCtx))
assert.Equal(t, 0, msgs.n)
}
type steerClaimFailingManager struct {
interfaces.StreamManager
}
func (s *steerClaimFailingManager) ClaimLiveRun(context.Context, string, string, string) error {
return errors.New("redis down")
}
type steerAppendFailingManager struct {
interfaces.StreamManager
}
func (s *steerAppendFailingManager) AppendSteerEvents(
context.Context, string, string, []interfaces.StreamEvent,
) error {
return errors.New("redis down")
}
func TestClaimNextSteerFollowUpClaimFailureRollsBackMessages(t *testing.T) {
ctx := t.Context()
inner := stream.NewMemoryStreamManager()
require.NoError(t, inner.SetLiveRun(ctx, "sess-1", "assist-A", "req-A"))
require.NoError(t, inner.AppendSteerEvents(ctx, "sess-1", "assist-A", []interfaces.StreamEvent{
steerEventWithDelivery("after-1", "do this next", steerDeliveryAfter),
}))
msgs := &steerPersistingMessageStub{}
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: msgs,
streamManager: &steerClaimFailingManager{StreamManager: inner},
}
followUp, ok := h.claimNextSteerFollowUp(ctx, &qaRequestContext{sessionID: "sess-1"},
&sseStreamContext{assistantMessage: &types.Message{ID: "assist-A"}})
assert.False(t, ok)
assert.Nil(t, followUp)
assert.Empty(t, msgs.byID, "ClaimLiveRun failure must not leave a follow-up turn in the database")
old, _, err := inner.GetSteerEvents(ctx, "sess-1", "assist-A", 0)
require.NoError(t, err)
require.Len(t, old, 1)
assert.False(t, steerEventConsumed(old[0]), "backlog must stay pending so a retry can claim it")
}
func TestRebindSteerKeepsEventWhenAppendFails(t *testing.T) {
ctx := t.Context()
inner := stream.NewMemoryStreamManager()
require.NoError(t, inner.SetLiveRun(ctx, "sess-1", "assist-A", "req-A"))
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{
msg: &types.Message{ID: "assist-B", SessionID: "sess-1", IsCompleted: false},
},
streamManager: &steerAppendFailingManager{StreamManager: inner},
}
evt := steerEventWithDelivery("late-1", "landed on A", steerDeliveryAfter)
require.NoError(t, inner.AppendSteerEvents(ctx, "sess-1", "assist-A", []interfaces.StreamEvent{evt}))
require.NoError(t, inner.ClaimLiveRun(ctx, "sess-1", "assist-B", "req-B"))
_, _, err := h.rebindSteerIfLiveRunMoved(ctx, "sess-1", "assist-A", evt)
require.Error(t, err)
old, _, err := inner.GetSteerEvents(ctx, "sess-1", "assist-A", 0)
require.NoError(t, err)
require.Len(t, old, 1)
assert.Equal(t, "late-1", old[0].ID)
}
func TestSteerMessageRejectsDifferentExpectedRun(t *testing.T) {
h := &Handler{
sessionService: &steerOwnedSessionStub{},
messageService: &steerMessageLookupStub{msg: &types.Message{ID: "new-run", IsCompleted: false}},
streamManager: &steerLiveRunLookupStub{assistantID: "new-run"},
}
w := postSteer(t, newSteerLiveRunRouter(h),
`{"query":"keep going","delivery":"inject","expected_assistant_message_id":"old-run"}`)
assert.Equal(t, http.StatusConflict, w.Code)
}
func TestSteerRetryFindsConsumedReceiptAfterRunCompleted(t *testing.T) {
mgr := stream.NewMemoryStreamManager()
ctx := context.Background()
id := "7c2f7062-c80a-480e-ac21-c509b6210936"
evt := steerEventWithDelivery(id, "more", steerDeliveryInject)
evt.Data[steerDataConsumed] = true
require.NoError(t, mgr.AppendSteerEvents(ctx, "sess-1", "old-run", []interfaces.StreamEvent{evt}))
h := &Handler{
sessionService: &steerOwnedSessionStub{}, messageService: &steerMessageLookupStub{}, streamManager: mgr,
}
w := postSteer(t, newSteerLiveRunRouter(h),
`{"query":"more","delivery":"inject","expected_assistant_message_id":"old-run","steer_id":"`+id+`"}`)
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "already_injected")
assert.NotContains(t, w.Body.String(), "new_run")
}
@@ -0,0 +1,151 @@
package session
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"academy/internal/agent"
agenttools "academy/internal/agent/tools"
"academy/internal/application/repository"
"academy/internal/application/service"
"academy/internal/event"
"academy/internal/models/api"
"academy/internal/models/api/openaicompletions"
"academy/internal/stream"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// Only the injected SQLite failure is removed; all successful writes use
// the production message service and repositories.
type recoveringSteerMessages struct {
interfaces.MessageService
db *gorm.DB
}
func (s *recoveringSteerMessages) CreateMessage(ctx context.Context, msg *types.Message) (*types.Message, error) {
created, err := s.MessageService.CreateMessage(ctx, msg)
if err != nil {
s.db.Exec("DROP TRIGGER IF EXISTS audit_fail_first_steer")
}
return created, err
}
func TestSteerOrderWithSQLiteFailure(t *testing.T) {
for _, failFirst := range []bool{false, true} {
t.Run(fmt.Sprintf("fail_first_%t", failFirst), func(t *testing.T) {
runSteerOrderIntegration(t, failFirst)
})
}
}
func steerOrderDatabase(t *testing.T, failFirst bool) (*gorm.DB, string) {
t.Helper()
dsn := "file:" + strings.ReplaceAll(t.Name(), "/", "_") + "?mode=memory&cache=shared"
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { _ = sqlDB.Close() })
require.NoError(t, db.AutoMigrate(&types.Session{}, &types.Message{}))
auditSession := &types.Session{TenantID: 1}
require.NoError(t, db.Create(auditSession).Error)
if failFirst {
require.NoError(t, db.Exec(`CREATE TRIGGER audit_fail_first_steer BEFORE INSERT ON messages
WHEN NEW.content = 'OLDER: use option A'
BEGIN SELECT RAISE(FAIL, 'injected one-shot write failure'); END`).Error)
}
return db, auditSession.ID
}
type steerOrderModelRequests struct {
mu sync.Mutex
requests []string
}
func (a *steerOrderModelRequests) serveHTTP(w http.ResponseWriter, r *http.Request) {
var body struct {
Messages []struct {
Content string `json:"content"`
} `json:"messages"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var text strings.Builder
for _, m := range body.Messages {
text.WriteString(m.Content)
text.WriteByte('\n')
}
a.mu.Lock()
a.requests = append(a.requests, text.String())
a.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
_, _ = fmt.Fprint(w,
`data: {"choices":[{"index":0,"delta":{"content":"Acknowledged"},"finish_reason":"stop"}]}`+"\n\n")
}
func (a *steerOrderModelRequests) assertOrder(t *testing.T, db *gorm.DB, failFirst bool) {
t.Helper()
var rows []types.Message
require.NoError(t, db.Order("created_at").Find(&rows).Error)
var order []string
for _, row := range rows {
order = append(order, row.Content)
}
a.mu.Lock()
wire := append([]string(nil), a.requests...)
a.mu.Unlock()
require.NotEmpty(t, wire)
last := wire[len(wire)-1]
t.Logf("fail_first=%t; persisted_order=%q; model_calls=%d; older_index=%d; newer_index=%d",
failFirst, order, len(wire), strings.Index(last, "OLDER:"), strings.Index(last, "NEWER:"))
require.Contains(t, last, "OLDER:")
require.Contains(t, last, "NEWER:")
require.Less(t, strings.Index(last, "OLDER:"), strings.Index(last, "NEWER:"),
"the model must receive the newer correction after the older instruction")
require.Equal(t, []string{"OLDER: use option A", "NEWER: replace A with option B"}, order,
"a failed write must not let the newer correction overtake the older instruction")
}
func runSteerOrderIntegration(t *testing.T, failFirst bool) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
db, sessionID := steerOrderDatabase(t, failFirst)
msgs := &recoveringSteerMessages{MessageService: service.NewMessageService(
repository.NewMessageRepository(db), repository.NewSessionRepository(db), nil, nil, nil, nil, nil), db: db}
tenantCtx := context.WithValue(t.Context(), types.TenantIDContextKey, uint64(1))
ctx, cancel := context.WithTimeout(tenantCtx, 10*time.Second)
defer cancel()
mgr := stream.NewMemoryStreamManager()
require.NoError(t, mgr.AppendSteerEvents(ctx, sessionID, "assistant", []interfaces.StreamEvent{
steerEventWithDelivery("older", "OLDER: use option A", steerDeliveryInject),
steerEventWithDelivery("newer", "NEWER: replace A with option B", steerDeliveryInject),
}))
sink := newSteerSink(ctx, sessionID, "request", &types.Message{ID: "assistant"}, msgs, mgr)
captured := &steerOrderModelRequests{}
server := httptest.NewServer(http.HandlerFunc(captured.serveHTTP))
defer server.Close()
model := openaicompletions.New(openaicompletions.Config{Endpoint: api.Endpoint{
BaseURL: server.URL, Model: "order-audit", Client: server.Client(),
}})
engine := agent.NewAgentEngine(&types.AgentConfig{MaxIterations: 3, MaxContextTokens: 100000},
model, agenttools.NewToolRegistry(), event.NewEventBus(), nil, nil, sessionID,
"Follow the user's latest correction.")
require.NotNil(t, engine)
engine.SetSteerSink(sink)
_, err := engine.Execute(ctx, sessionID, "assistant", "Choose an option.", nil)
require.NoError(t, err)
captured.assertOrder(t, db, failFirst)
}
@@ -0,0 +1,198 @@
package session
import (
"net/http/httptest"
"testing"
"time"
"academy/internal/stream"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newSteerWiringGinContext builds the minimal gin context setupSSEStream
// needs (setSSEHeaders writes to it immediately).
func newSteerWiringGinContext() *gin.Context {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/", nil)
return c
}
// TestSetupSSEStreamMirrorsSteerSinkOntoRequestContext is the regression guard
// for the wiring bug where the sink was created on sseStreamContext but
// buildQARequest read qaRequestContext.steerSink — which nobody ever set — so
// queued steer messages were never handed to the engine and sat in the
// sub-list forever. The sink must be reachable from BOTH holders.
func TestSetupSSEStreamMirrorsSteerSinkOntoRequestContext(t *testing.T) {
streams := stream.NewMemoryStreamManager()
h := &Handler{streamManager: streams}
assistantMessage := &types.Message{
ID: "assist-1",
SessionID: "sess-1",
Role: "assistant",
CreatedAt: time.Now(),
}
reqCtx := &qaRequestContext{
c: newSteerWiringGinContext(),
ctx: t.Context(),
sessionID: "sess-1",
requestID: "req-1",
session: &types.Session{ID: "sess-1"},
customAgent: &types.CustomAgent{ID: "agent-1"},
assistantMessage: assistantMessage,
}
streamCtx := h.setupSSEStream(reqCtx, false, qaModeAgent)
require.NotNil(t, streamCtx, "setupSSEStream returned nil")
require.NotNil(t, streamCtx.steerSink, "streamCtx.steerSink must be created for agent runs")
assert.NotNil(t, reqCtx.steerSink,
"reqCtx.steerSink must mirror the streamCtx sink — buildQARequest reads it; "+
"if this is nil the engine never receives a SteerSink and queued messages are silently dropped")
assert.Same(t, streamCtx.steerSink, reqCtx.steerSink,
"both holders must point at the same sink instance")
// The built QA request must carry the sink through to the service layer.
qaReq := reqCtx.buildQARequest()
assert.NotNil(t, qaReq.SteerSink,
"QARequest.SteerSink must be set for agent runs — nil here means the engine runs without mid-run injection")
// The live-run marker must be published through the StreamManager, not a
// process-local map: a steer request that lands on another replica has
// to find this run instead of reporting "no run is live" and starting a
// duplicate turn.
liveID, liveReq, err := streams.GetLiveRun(t.Context(), "sess-1")
require.NoError(t, err)
assert.Equal(t, "assist-1", liveID, "agent run must be published as the session's live run")
assert.Equal(t, "req-1", liveReq)
}
// TestSetupSSEStreamNoSinkWithoutCustomAgent pins the negative case: runs
// without a custom agent (quick-answer) get no sink, matching the previous
// behaviour.
func TestSetupSSEStreamNoSinkWithoutCustomAgent(t *testing.T) {
streams := stream.NewMemoryStreamManager()
h := &Handler{streamManager: streams}
reqCtx := &qaRequestContext{
ctx: t.Context(),
c: newSteerWiringGinContext(),
sessionID: "sess-2",
requestID: "req-2",
session: &types.Session{ID: "sess-2"},
customAgent: nil,
assistantMessage: &types.Message{ID: "assist-2", SessionID: "sess-2", Role: "assistant", CreatedAt: time.Now()},
}
streamCtx := h.setupSSEStream(reqCtx, false, qaModeNormal)
require.NotNil(t, streamCtx)
assert.Nil(t, streamCtx.steerSink)
assert.Nil(t, reqCtx.steerSink)
qaReq := reqCtx.buildQARequest()
assert.Nil(t, qaReq.SteerSink)
// Quick-answer turns must not claim the session either: there is no
// engine loop to drain a queue, so a steer request pointed here would
// park messages that never run.
liveID, _, err := streams.GetLiveRun(t.Context(), "sess-2")
require.NoError(t, err)
assert.Empty(t, liveID, "non-agent run must not be published as the live run")
}
// A custom agent configured as quick-answer still has customAgent != nil, but
// executeQA runs KnowledgeQA (qaModeNormal). Publishing a steer sink / live
// marker there parks /steer messages on a turn with no engine loop and no
// teardown ClearLiveRun.
func TestSetupSSEStreamNoSinkForQuickAnswerCustomAgent(t *testing.T) {
streams := stream.NewMemoryStreamManager()
h := &Handler{streamManager: streams}
reqCtx := &qaRequestContext{
ctx: t.Context(),
c: newSteerWiringGinContext(),
sessionID: "sess-3",
requestID: "req-3",
session: &types.Session{ID: "sess-3"},
customAgent: &types.CustomAgent{
ID: "custom-quick",
Config: types.CustomAgentConfig{AgentMode: types.AgentModeQuickAnswer},
},
assistantMessage: &types.Message{
ID: "assist-3", SessionID: "sess-3", Role: "assistant", CreatedAt: time.Now(),
},
}
streamCtx := h.setupSSEStream(reqCtx, false, qaModeNormal)
require.NotNil(t, streamCtx)
assert.Nil(t, streamCtx.steerSink,
"KnowledgeQA / quick-answer turns must not get a steer sink")
assert.Nil(t, reqCtx.steerSink)
assert.Nil(t, reqCtx.buildQARequest().SteerSink)
liveID, _, err := streams.GetLiveRun(t.Context(), "sess-3")
require.NoError(t, err)
assert.Empty(t, liveID,
"quick-answer custom-agent turns must not publish a live-run marker")
}
// KnowledgeQA can still resolve a smart-reasoning agent_id (API / stale
// client). The teardown that clears the live marker only runs for
// qaModeAgent, so a live marker here would never be released.
func TestSetupSSEStreamNoSinkForKnowledgeQAEvenWithAgentModeAgent(t *testing.T) {
streams := stream.NewMemoryStreamManager()
h := &Handler{streamManager: streams}
reqCtx := &qaRequestContext{
ctx: t.Context(),
c: newSteerWiringGinContext(),
sessionID: "sess-4",
requestID: "req-4",
session: &types.Session{ID: "sess-4"},
customAgent: &types.CustomAgent{
ID: "custom-react",
Config: types.CustomAgentConfig{AgentMode: types.AgentModeSmartReasoning},
},
assistantMessage: &types.Message{
ID: "assist-4", SessionID: "sess-4", Role: "assistant", CreatedAt: time.Now(),
},
}
streamCtx := h.setupSSEStream(reqCtx, false, qaModeNormal)
require.NotNil(t, streamCtx)
assert.Nil(t, streamCtx.steerSink)
liveID, _, err := streams.GetLiveRun(t.Context(), "sess-4")
require.NoError(t, err)
assert.Empty(t, liveID)
}
func TestSetupSSEStreamDoesNotWriteSSEWhenLiveRunFails(t *testing.T) {
streams := stream.NewMemoryStreamManager()
require.NoError(t, streams.SetLiveRun(t.Context(), "sess-5", "other-assist", "req-other"))
h := &Handler{streamManager: streams}
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/", nil)
reqCtx := &qaRequestContext{
c: c,
ctx: t.Context(),
sessionID: "sess-5",
requestID: "req-5",
session: &types.Session{ID: "sess-5"},
customAgent: &types.CustomAgent{ID: "agent-1"},
assistantMessage: &types.Message{
ID: "assist-5", SessionID: "sess-5", Role: "assistant", CreatedAt: time.Now(),
},
}
streamCtx := h.setupSSEStream(reqCtx, false, qaModeAgent)
require.True(t, streamCtx.liveRunFailed)
assert.NotEqual(t, "text/event-stream", w.Header().Get("Content-Type"),
"SetLiveRun failure must not start an SSE response the client cannot recover from")
}
+517
View File
@@ -0,0 +1,517 @@
package session
import (
"context"
stderrors "errors"
"fmt"
"net/http"
"time"
"academy/internal/errors"
"academy/internal/event"
"academy/internal/logger"
"academy/internal/storageurl"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// ContinueStream godoc
// @Summary 继续流式响应
// @Description 继续获取正在进行的流式响应
// @Tags 问答
// @Accept json
// @Produce text/event-stream
// @Param session_id path string true "会话ID"
// @Param message_id query string true "消息ID"
// @Param resume_pending_id query string false "等待此审批恢复后的事件流"
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
// @Success 200 {string} string "SSE 事件流"
// @Failure 404 {object} errors.AppError "会话或消息不存在"
// @Failure 409 {object} errors.AppError "审批恢复后的事件流尚未就绪"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/continue-stream/{session_id} [get]
func (h *Handler) ContinueStream(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start continuing stream response processing")
// Get session ID from URL parameter
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Get message ID from query parameter
messageID := secutils.SanitizeForLog(c.Query("message_id"))
if messageID == "" {
logger.Error(ctx, "Message ID is empty")
c.Error(errors.NewBadRequestError("Missing message ID"))
return
}
logger.Infof(ctx, "Continuing stream, session ID: %s, message ID: %s", sessionID, messageID)
// Resolve before any SSE header is written so an invalid resource_urls value
// is still reportable as a normal 400 JSON error.
resourceRewriter, err := h.resolveStreamRewriter(c)
if err != nil {
logger.Warnf(ctx, "Rejected resource URL mode: %v", err)
_ = c.Error(err)
return
}
// Verify that the session exists and belongs to this tenant
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
c.Error(errors.NewNotFoundError(err.Error()))
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
// Get the incomplete message
message, err := h.messageService.GetMessage(ctx, sessionID, messageID)
if err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
// PR #1309 plumbed user-scope into messageService.GetMessage's
// session existence check; non-owner / wrong-user lookups now
// surface as ErrSessionNotFound. Map to 404 so clients can tell
// "wrong URL" from a real 5xx instead of seeing a generic 500.
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
if stderrors.Is(err, gorm.ErrRecordNotFound) {
// The message_id doesn't exist (e.g. a wrong / non-persisted id, or an
// expired replay buffer). That is a client error, not a server fault:
// return 404 so callers read resource.not_found (a permanent condition
// they must not retry) instead of a retryable 5xx. Mirrors the
// ErrSessionNotFound branch above and the kb/doc/chunk not-found fix.
logger.Warnf(ctx, "Message not found, session ID: %s, message ID: %s", sessionID, messageID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
if message == nil {
logger.Warnf(ctx, "Incomplete message not found, session ID: %s, message ID: %s", sessionID, messageID)
c.JSON(http.StatusNotFound, gin.H{
"success": false,
"error": "Incomplete message not found",
})
return
}
// Get initial events from stream (offset 0)
events, currentOffset, err := h.streamManager.GetEvents(ctx, sessionID, messageID, 0)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(fmt.Sprintf("Failed to get stream data: %s", err.Error())))
return
}
if len(events) == 0 {
logger.Warnf(ctx, "No events found in stream, session ID: %s, message ID: %s", sessionID, messageID)
c.JSON(http.StatusNotFound, gin.H{
"success": false,
"error": "No stream events found",
})
return
}
// A scheduler may not have reset the previous segment yet. Never replay
// its terminal event as if the just-approved continuation had completed.
if pendingID := c.Query("resume_pending_id"); pendingID != "" && !message.IsCompleted {
ready := false
for _, evt := range events {
if (evt.Type == types.ResponseTypeAgentQuery && evt.Data["resume_pending_id"] == pendingID) ||
(evt.Type == types.ResponseTypeRunResumed && evt.Data["pending_id"] == pendingID) {
ready = true
break
}
}
if !ready {
c.JSON(http.StatusConflict, gin.H{"success": false, "error": "The resumed stream is not ready yet"})
return
}
}
logger.Infof(
ctx, "Preparing to replay %d events and continue streaming, session ID: %s, message ID: %s",
len(events), sessionID, messageID,
)
// Set headers for SSE
setSSEHeaders(c)
// Check if stream is already completed
streamCompleted := false
for _, evt := range events {
if evt.Type == "complete" {
streamCompleted = true
break
}
}
// Replay existing events, a segment's worth of chunks per frame
replay := coalesceReplayEvents(events)
logger.Debugf(ctx, "Replaying %d existing events as %d frames", len(events), len(replay))
for _, evt := range replay {
emitStreamEvent(ctx, c, evt, message.RequestID, resourceRewriter)
}
// If stream is already completed, send final event and return
if streamCompleted {
logger.Infof(ctx, "Stream already completed, session ID: %s, message ID: %s", sessionID, messageID)
sendCompletionEvent(c, message.RequestID)
return
}
// Continue polling for new events
logger.Debug(ctx, "Starting event update monitoring")
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
heartbeat := time.NewTicker(10 * time.Second)
defer heartbeat.Stop()
for {
select {
case <-c.Request.Context().Done():
logger.Debug(ctx, "Client connection closed")
return
case <-heartbeat.C:
c.SSEvent("message", gin.H{"response_type": "heartbeat"})
c.Writer.Flush()
case <-ticker.C:
// Get new events from current offset
newEvents, newOffset, err := h.streamManager.GetEvents(ctx, sessionID, messageID, currentOffset)
if err != nil {
logger.Errorf(ctx, "Failed to get new events: %v", err)
flushHeldStreamContent(ctx, c, message.RequestID, resourceRewriter)
return
}
// Send new events
streamCompletedNow := false
for _, evt := range newEvents {
// Check for completion event
if evt.Type == "complete" {
streamCompletedNow = true
}
emitStreamEvent(ctx, c, evt, message.RequestID, resourceRewriter)
}
// Update offset
currentOffset = newOffset
// If stream completed, send final event and exit
if streamCompletedNow {
logger.Infof(ctx, "Stream completed, session ID: %s, message ID: %s", sessionID, messageID)
sendCompletionEvent(c, message.RequestID)
return
}
}
}
}
// StopSession godoc
// @Summary 停止生成
// @Description 停止当前正在进行的生成任务
// @Tags 问答
// @Accept json
// @Produce json
// @Param session_id path string true "会话ID"
// @Param request body StopSessionRequest true "停止请求"
// @Success 200 {object} map[string]interface{} "停止成功"
// @Failure 404 {object} errors.AppError "会话或消息不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/stop [post]
func (h *Handler) StopSession(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
c.JSON(400, gin.H{"error": "Session ID is required"})
return
}
// Parse request body to get message_id
var req StopSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
})
c.JSON(400, gin.H{"error": "message_id is required"})
return
}
assistantMessageID := secutils.SanitizeForLog(req.MessageID)
logger.Infof(ctx, "Stop generation request for session: %s, message: %s", sessionID, assistantMessageID)
// Get tenant ID from context
tenantID, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
logger.Error(ctx, "Failed to get tenant ID")
c.JSON(401, gin.H{"error": "Unauthorized"})
return
}
tenantIDUint := tenantID.(uint64)
// Verify message ownership and status
message, err := h.messageService.GetMessage(ctx, sessionID, assistantMessageID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"message_id": assistantMessageID,
})
c.JSON(404, gin.H{"error": "Message not found"})
return
}
// Verify message belongs to this session (double check)
if message.SessionID != sessionID {
logger.Warnf(ctx, "Message %s does not belong to session %s", assistantMessageID, sessionID)
c.JSON(403, gin.H{"error": "Message does not belong to this session"})
return
}
// Verify message belongs to the current tenant. Stopping generation mutates
// an in-flight run, so use the strict owner scope: a tenant admin may read an
// API-key session but must not be able to interrupt its (external) API calls.
session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
})
c.JSON(404, gin.H{"error": "Session not found"})
return
}
if session.TenantID != tenantIDUint {
logger.Warnf(ctx, "Session %s does not belong to tenant %d", sessionID, tenantIDUint)
c.JSON(403, gin.H{"error": "Access denied"})
return
}
if h.stopCollaboration != nil {
if err := h.stopCollaboration(ctx, sessionID, assistantMessageID); err != nil {
c.JSON(500, gin.H{"error": "Failed to stop delegated tasks"})
return
}
}
// Check if message is already completed (stopped)
if message.IsCompleted {
logger.Infof(ctx, "Message %s is already completed, no need to stop", assistantMessageID)
c.JSON(200, gin.H{
"success": true,
"message": "Message already completed",
})
return
}
// Write stop event to StreamManager for distributed support
stopEvent := interfaces.StreamEvent{
ID: fmt.Sprintf("stop-%d", time.Now().UnixNano()),
Type: types.ResponseType(event.EventStop),
Content: "",
Done: true,
Timestamp: time.Now(),
Data: map[string]interface{}{
"session_id": sessionID,
"message_id": assistantMessageID,
"reason": "user_requested",
},
}
if err := h.streamManager.AppendEvent(ctx, sessionID, assistantMessageID, stopEvent); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": sessionID,
"message_id": assistantMessageID,
})
c.JSON(500, gin.H{"error": "Failed to write stop event"})
return
}
logger.Infof(ctx, "Stop event written successfully for session: %s, message: %s", sessionID, assistantMessageID)
h.notifyBackgroundStop(ctx, session)
c.JSON(200, gin.H{
"success": true,
"message": "Generation stopped",
})
}
// handleAgentEventsForSSE handles agent events for SSE streaming using an existing handler
// The handler is already subscribed to events and AgentQA is already running
// This function polls StreamManager and pushes events to SSE, allowing graceful handling of disconnections
// waitForTitle: if true, wait for title event after completion (for new sessions without title)
func (h *Handler) handleAgentEventsForSSE(
ctx context.Context,
c *gin.Context,
sessionID, assistantMessageID, requestID string,
eventBus *event.EventBus,
waitForTitle bool,
resourceRewriter *storageurl.StreamRewriter,
) {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
heartbeat := time.NewTicker(10 * time.Second)
defer heartbeat.Stop()
lastOffset := 0
log := logger.GetLogger(ctx)
// Agent mode releases the sandbox turn lease, and therefore cancels ctx,
// before the completion event is published. Polling Redis with that
// context drops the terminal event and the client waits at the end of
// the answer. Client disconnect is still observed on the request below.
pollCtx := context.WithoutCancel(ctx)
log.Infof("Starting pull-based SSE streaming for session=%s, message=%s", sessionID, assistantMessageID)
for {
select {
case <-c.Request.Context().Done():
// Connection closed, exit gracefully without panic
log.Infof(
"Client disconnected, stopping SSE streaming for session=%s, message=%s",
sessionID,
assistantMessageID,
)
return
case <-heartbeat.C:
c.SSEvent("message", gin.H{"response_type": "heartbeat"})
c.Writer.Flush()
case <-ticker.C:
// Get new events from StreamManager using offset
events, newOffset, err := h.streamManager.GetEvents(pollCtx, sessionID, assistantMessageID, lastOffset)
if err != nil {
log.Warnf("Failed to get events from stream: %v", err)
continue
}
// Send any new events
streamCompleted := false
titleReceived := false
for _, evt := range events {
// Check for stop event
if evt.Type == types.ResponseType(event.EventStop) {
log.Infof("Detected stop event, triggering stop via EventBus for session=%s", sessionID)
// Emit stop event to the EventBus to trigger context cancellation
if eventBus != nil {
eventBus.Emit(ctx, event.Event{
Type: event.EventStop,
SessionID: sessionID,
Data: event.StopData{
SessionID: sessionID,
MessageID: assistantMessageID,
Reason: "user_requested",
},
})
}
// Release any buffered tail first: the answer generated
// before the stop is still the user's content, and in
// public resource URL mode part of it may be sitting in
// the holdback buffer.
flushHeldStreamContent(ctx, c, requestID, resourceRewriter)
// Send stop notification to frontend
c.SSEvent("message", &types.StreamResponse{
ID: requestID,
ResponseType: "stop",
Content: "Generation stopped by user",
Done: true,
})
c.Writer.Flush()
return
}
// Check for completion event
if evt.Type == "complete" {
streamCompleted = true
}
// Check for title event
if evt.Type == types.ResponseTypeSessionTitle {
titleReceived = true
}
// Check if connection is still alive before writing. Build the
// payload only after this check: in public resource URL mode
// building consumes the chunk into the holdback buffer, so an
// early return here would drop it.
if c.Request.Context().Err() != nil {
log.Info("Connection closed during event sending, stopping")
return
}
emitStreamEvent(ctx, c, evt, requestID, resourceRewriter)
}
// Update offset
lastOffset = newOffset
// Check if stream is completed - wait for title event only if needed and not already received
if streamCompleted {
if waitForTitle && !titleReceived {
log.Infof("Stream completed for session=%s, message=%s, waiting for title event", sessionID, assistantMessageID)
// Wait up to 3 seconds for title event after completion
titleTimeout := time.After(3 * time.Second)
titleWaitLoop:
for {
select {
case <-titleTimeout:
log.Info("Title wait timeout, closing stream")
break titleWaitLoop
case <-c.Request.Context().Done():
log.Info("Connection closed while waiting for title")
return
default:
// Check for new events (title event)
events, newOff, err := h.streamManager.GetEvents(c.Request.Context(), sessionID, assistantMessageID, lastOffset)
if err != nil {
log.Warnf("Error getting events while waiting for title: %v", err)
break titleWaitLoop
}
if len(events) > 0 {
for _, evt := range events {
emitStreamEvent(ctx, c, evt, requestID, resourceRewriter)
// If we got the title, we can exit
if evt.Type == types.ResponseTypeSessionTitle {
log.Infof("Title event received: %s", evt.Content)
break titleWaitLoop
}
}
lastOffset = newOff
} else {
// No events, wait a bit before checking again
time.Sleep(100 * time.Millisecond)
}
}
}
} else {
log.Infof("Stream completed for session=%s, message=%s", sessionID, assistantMessageID)
}
sendCompletionEvent(c, requestID)
return
}
}
}
}
@@ -0,0 +1,70 @@
package session
import (
"context"
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// cancelAfterFirstReadStream mimics Redis: a canceled context fails the read.
// The first successful read cancels the caller's context, the way agent mode
// releases the sandbox turn lease before the completion event is published.
type cancelAfterFirstReadStream struct {
interfaces.StreamManager
events []interfaces.StreamEvent
cancel context.CancelFunc
reads int
}
func (s *cancelAfterFirstReadStream) GetEvents(
ctx context.Context, _, _ string, fromOffset int,
) ([]interfaces.StreamEvent, int, error) {
if err := ctx.Err(); err != nil {
return nil, fromOffset, fmt.Errorf("failed to get events from Redis: %w", err)
}
s.reads++
if s.reads == 1 {
s.cancel()
return s.events[:1], 1, nil
}
if fromOffset >= len(s.events) {
return nil, len(s.events), nil
}
return s.events[fromOffset:], len(s.events), nil
}
func TestHandleAgentEventsForSSE_DrainsCompletionAfterTurnContextCanceled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
h := &Handler{streamManager: &cancelAfterFirstReadStream{
cancel: cancel,
events: []interfaces.StreamEvent{
{ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "你好", Done: true},
{ID: "complete-1", Type: types.ResponseTypeComplete, Done: true},
},
}}
c, recorder := newTestGinContext(t, "")
done := make(chan struct{})
go func() {
h.handleAgentEventsForSSE(
ctx, c, "sess1", "msg1", "req-1", nil, false, publicStreamRewriter())
close(done)
}()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("SSE poll kept using the cancelled turn context and never delivered completion")
}
body := recorder.Body.String()
require.Contains(t, body, "你好")
assert.Contains(t, body, `"response_type":"complete"`)
}
@@ -0,0 +1,50 @@
package session
import (
"encoding/json"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBuildStreamResponsePromotesUsageOnCompleteEvents(t *testing.T) {
usage := &types.TokenUsage{PromptTokens: 100, CompletionTokens: 20, TotalTokens: 120}
response := buildStreamResponse(interfaces.StreamEvent{
Type: types.ResponseTypeComplete,
Done: true,
Data: map[string]interface{}{"total_steps": 3, "usage": usage},
Usage: usage,
}, "req-1")
require.NotNil(t, response.Usage)
assert.Equal(t, 120, response.Usage.TotalTokens)
assert.Equal(t, usage, response.Data["usage"])
}
func TestBuildStreamResponseLeavesUsageNilWhenAbsent(t *testing.T) {
response := buildStreamResponse(interfaces.StreamEvent{
Type: types.ResponseTypeAnswer,
Data: map[string]interface{}{"event_id": "e-1"},
}, "req-1")
assert.Nil(t, response.Usage)
}
func TestStreamEventUsageSurvivesJSONRoundTrip(t *testing.T) {
// The stream manager persists events as JSON (Redis) before the SSE loop
// reads them back — the typed usage must survive that round trip.
usage := &types.TokenUsage{PromptTokens: 100, CompletionTokens: 20, TotalTokens: 120}
usage.SetPromptCacheUsage(80, 0, 20, true)
raw, err := json.Marshal(interfaces.StreamEvent{Type: types.ResponseTypeComplete, Usage: usage})
require.NoError(t, err)
var restored interfaces.StreamEvent
require.NoError(t, json.Unmarshal(raw, &restored))
require.NotNil(t, restored.Usage)
assert.Equal(t, *usage, *restored.Usage)
}
@@ -0,0 +1,81 @@
package session
import (
"context"
"testing"
"time"
"academy/internal/event"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestSuspendedRunIsSavedIncompleteAndAnnounced(t *testing.T) {
messages := &imageCompletionMessages{}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
message := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
ctx := types.WithExecutionTenant(context.Background(), 1)
streamHandler := h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), message, bus)
expires := time.Now().Add(time.Hour)
suspension := &types.PromptSuspension{
PromptID: "p1", Kind: types.AgentPromptKindToolApproval, ExpiresAt: &expires,
}
steps := []types.AgentStep{{Iteration: 0, Thought: "checking first", ToolCalls: []types.ToolCall{
{ID: "call-a", Name: "first_tool", Result: &types.ToolResult{Success: true, Output: "ok"}},
}}}
require.NoError(t, bus.Emit(ctx, event.Event{
ID: "complete-1",
Type: event.EventAgentComplete,
Data: event.AgentCompleteData{
MessageID: "m", FinalAnswer: "must not be shown", AgentSteps: steps, Suspended: suspension,
},
}))
require.Equal(t, suspension, streamHandler.Suspension())
require.Empty(t, stream.events, "nothing is announced before the message is saved")
h.completeStreamAssistantMessage(ctx, &sseStreamContext{
eventBus: bus, streamHandler: streamHandler, assistantMessage: message,
}, "the question", "u1")
require.NotNil(t, messages.saved)
require.False(t, messages.saved.IsCompleted)
require.Equal(t, types.MessageRunStateAwaitingInput, messages.saved.RunState)
require.Len(t, messages.saved.AgentSteps, 1)
require.Len(t, stream.events, 2, "no fallback answer for a suspended run")
announced := stream.events[0]
require.Equal(t, types.ResponseTypeRunSuspended, announced.Type)
require.Equal(t, "p1", announced.Data["pending_id"])
require.Equal(t, types.AgentPromptKindToolApproval, announced.Data["kind"])
require.Equal(t, &expires, announced.Data["expires_at"])
complete := stream.events[1]
require.Equal(t, types.ResponseTypeComplete, complete.Type)
require.True(t, complete.Done)
require.Equal(t, suspension, complete.Data["suspended"])
}
func TestDetachedRunDoesNotOverwriteOrAnnounceCompletion(t *testing.T) {
messages := &imageCompletionMessages{}
stream := &imageCompletionStream{}
h := &Handler{messageService: messages, streamManager: stream}
bus := event.NewEventBus()
message := &types.Message{ID: "m", SessionID: "s", Role: "assistant", Content: "original"}
ctx := types.WithExecutionTenant(t.Context(), 1)
handler := h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), message, bus)
suspension := &types.PromptSuspension{PromptID: "p", Detached: true}
require.NoError(t, bus.Emit(ctx, event.Event{
Type: event.EventAgentComplete,
Data: event.AgentCompleteData{MessageID: "m", FinalAnswer: "stale result", Suspended: suspension},
}))
h.completeStreamAssistantMessage(ctx, &sseStreamContext{
eventBus: bus, streamHandler: handler, assistantMessage: message,
}, "question", "u")
require.Equal(t, "original", message.Content)
require.False(t, message.IsCompleted)
require.Nil(t, messages.saved)
require.Empty(t, stream.events)
}
@@ -0,0 +1,128 @@
package session
import (
"context"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// attachmentMsgStub implements just the two MessageService methods used by
// persistResolvedAttachmentContent; the rest are inherited from the embedded
// interface and panic if unexpectedly called.
type attachmentMsgStub struct {
interfaces.MessageService
stored *types.Message
updated *types.Message
updateCalls int
}
func (s *attachmentMsgStub) GetMessage(_ context.Context, _ string, _ string) (*types.Message, error) {
return s.stored, nil
}
func (s *attachmentMsgStub) UpdateMessage(_ context.Context, message *types.Message) error {
s.updateCalls++
s.updated = message
return nil
}
func newAttachmentReqCtx() *qaRequestContext {
return &qaRequestContext{
sessionID: "sess-1",
userMessageID: "user-msg-1",
session: &types.Session{TenantID: 42},
}
}
// TestPersistResolvedAttachmentContent_EnrichesMatchingAttachments is the core
// regression guard for PR #2086: the user message is created with
// metadata-only attachment entries, and the parsed content selected after the
// SSE stream starts must be written back so multi-turn (Agent-mode) history can
// replay it via the Attachments column.
func TestPersistResolvedAttachmentContent_EnrichesMatchingAttachments(t *testing.T) {
stub := &attachmentMsgStub{
stored: &types.Message{
ID: "user-msg-1",
SessionID: "sess-1",
Role: "user",
Attachments: types.MessageAttachments{
{ID: "doc-1", FileName: "report.pdf", FileType: ".pdf"},
// Legacy inline upload without an ID must stay untouched.
{FileName: "note.txt", FileType: ".txt", Content: "legacy inline"},
},
},
}
h := &Handler{messageService: stub}
resolved := types.MessageAttachments{
{
ID: "doc-1", FileName: "report.pdf", FileType: ".pdf",
Content: "parsed body text", ContentMode: "selected_chunks",
SelectedChunks: 1, TotalChunks: 3, TokenCount: 12,
},
}
h.persistResolvedAttachmentContent(context.Background(), newAttachmentReqCtx(), resolved)
require.Equal(t, 1, stub.updateCalls, "matching attachment must trigger one persist")
require.NotNil(t, stub.updated)
require.Len(t, stub.updated.Attachments, 2)
assert.Equal(t, "parsed body text", stub.updated.Attachments[0].Content)
assert.Equal(t, "selected_chunks", stub.updated.Attachments[0].ContentMode)
assert.Equal(t, 3, stub.updated.Attachments[0].TotalChunks)
// Legacy inline attachment (no ID) is preserved verbatim.
assert.Equal(t, "legacy inline", stub.updated.Attachments[1].Content)
}
func TestPersistResolvedAttachmentContent_NoMatchSkipsUpdate(t *testing.T) {
stub := &attachmentMsgStub{
stored: &types.Message{
ID: "user-msg-1", SessionID: "sess-1", Role: "user",
Attachments: types.MessageAttachments{{ID: "doc-1", FileName: "a.pdf"}},
},
}
h := &Handler{messageService: stub}
resolved := types.MessageAttachments{{ID: "doc-other", Content: "x"}}
h.persistResolvedAttachmentContent(context.Background(), newAttachmentReqCtx(), resolved)
assert.Equal(t, 0, stub.updateCalls, "no matching ID must not persist")
}
func TestPersistResolvedAttachmentContent_GuardsEmptyInput(t *testing.T) {
stub := &attachmentMsgStub{}
h := &Handler{messageService: stub}
// No resolved attachments.
h.persistResolvedAttachmentContent(context.Background(), newAttachmentReqCtx(), nil)
// No user message ID.
rc := newAttachmentReqCtx()
rc.userMessageID = ""
h.persistResolvedAttachmentContent(context.Background(), rc, types.MessageAttachments{{ID: "doc-1", Content: "x"}})
assert.Equal(t, 0, stub.updateCalls)
}
func TestNormalizeTemporaryAttachmentIDs(t *testing.T) {
t.Run("rejects over limit before lookup", func(t *testing.T) {
ids := []string{"a", "b", "c", "d", "e", "f"}
_, err := normalizeTemporaryAttachmentIDs(ids)
require.Error(t, err)
assert.Contains(t, err.Error(), "at most 5")
})
t.Run("dedupes and drops empty", func(t *testing.T) {
got, err := normalizeTemporaryAttachmentIDs([]string{" a ", "", "b", "a", "c"})
require.NoError(t, err)
assert.Equal(t, []string{"a", "b", "c"}, got)
})
t.Run("allows max unique ids", func(t *testing.T) {
got, err := normalizeTemporaryAttachmentIDs([]string{"1", "2", "3", "4", "5"})
require.NoError(t, err)
assert.Equal(t, []string{"1", "2", "3", "4", "5"}, got)
})
}
@@ -0,0 +1,208 @@
package session
import (
"fmt"
"net/http"
"path/filepath"
"strings"
apperrors "academy/internal/errors"
"academy/internal/filetransport"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
)
// UploadTemporaryDocument accepts one multipart file and immediately returns
// a session-scoped document ID. Parsing continues in the document worker.
func (h *Handler) UploadTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := c.Param("session_id")
// Uploading attaches content to the session, so use the strict owner scope:
// a tenant admin may read an API-key session but must not add attachments.
if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
maxBytes := secutils.GetMaxFileSizeMB()*1024*1024 + 1024*1024
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
fileHeader, err := c.FormFile("file")
if err != nil {
c.Error(apperrors.NewBadRequestError(fmt.Sprintf("invalid attachment upload: %v", err)))
return
}
file, err := fileHeader.Open()
if err != nil {
c.Error(apperrors.NewBadRequestError("failed to open attachment"))
return
}
defer file.Close()
sourceTenantID, parseErr := types.ParseAgentSourceTenantID(c.PostForm(types.AgentSourceTenantIDParam))
if parseErr != nil {
c.Error(apperrors.NewBadRequestError(parseErr.Error()))
return
}
agent, resourceTenantID, _ := h.resolveAgent(ctx, c, c.PostForm("agent_id"), sourceTenantID)
if sourceTenantID != 0 && agent == nil {
c.Error(apperrors.NewNotFoundError("Shared agent not found"))
return
}
ext := strings.TrimPrefix(strings.ToLower(filepath.Ext(fileHeader.Filename)), ".")
options := types.TemporaryDocumentCreateOptions{ParserEngine: strings.TrimSpace(c.PostForm("parser_engine"))}
if agent != nil {
options.ResourceTenantID = resourceTenantID
// A shared agent parses in its owner's workspace, with the parser
// engines (and credentials) configured there: only the agent's own
// rules may pick one, not the caller.
if resourceTenantID != 0 && resourceTenantID != c.GetUint64(types.TenantIDContextKey.String()) {
options.ParserEngine = ""
}
if len(agent.Config.SupportedFileTypes) > 0 && !containsFileType(agent.Config.SupportedFileTypes, ext) {
c.Error(apperrors.NewBadRequestError("file type is not supported by this agent"))
return
}
if isAudioExtension(ext) {
if !agent.Config.AudioUploadEnabled || agent.Config.ASRModelID == "" {
c.Error(apperrors.NewBadRequestError("audio upload is not enabled or no ASR model is configured"))
return
}
options.ASRModelID = agent.Config.ASRModelID
}
// Resolve the parser engine from the agent's chat rules when the caller
// did not pass an explicit engine. Tenant-level rules remain the final
// fallback and are applied in the parse worker.
if options.ParserEngine == "" || options.ParserEngine == "auto" {
if engine := agent.Config.ResolveChatParserEngine(ext); engine != "" {
options.ParserEngine = engine
}
}
// Image understanding (caption/OCR) uses the agent's VLM model. Images
// always benefit; scanned/image-only documents only OCR when the agent
// enabled AttachmentImageUnderstanding (see parse worker threshold gate).
if agent.Config.ImageUploadEnabled && agent.Config.VLMModelID != "" {
options.VLMModelID = agent.Config.VLMModelID
options.ImageUnderstanding = agent.Config.AttachmentImageUnderstanding
options.OCRMaxPages = agent.Config.AttachmentOCRMaxPages
}
}
document, err := h.temporaryDocuments.Create(
ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID,
fileHeader.Filename, fileHeader.Header.Get("Content-Type"), fileHeader.Size, file, options,
)
if err != nil {
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": document.ForClient()})
}
func (h *Handler) ListTemporaryDocuments(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
documents, err := h.temporaryDocuments.List(ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID)
if err != nil {
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
for i := range documents {
documents[i] = documents[i].ForClient()
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": documents})
}
func (h *Handler) GetTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
document, err := h.temporaryDocuments.Get(ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID, c.Param("attachment_id"))
if err != nil {
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
if document == nil {
c.Error(apperrors.NewNotFoundError("Attachment not found"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": document.ForClient()})
}
func (h *Handler) PreviewTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
if _, err := h.sessionService.GetSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
attachmentID := secutils.SanitizeForLog(c.Param("attachment_id"))
if attachmentID == "" {
c.Error(apperrors.NewBadRequestError("Attachment ID cannot be empty"))
return
}
file, filename, err := h.temporaryDocuments.OpenFile(
ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID, attachmentID,
)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "not found") {
c.Error(apperrors.NewNotFoundError("Attachment not found"))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(apperrors.NewInternalServerError("Failed to retrieve attachment").WithDetails(err.Error()))
return
}
if err := filetransport.Serve(c.Writer, c.Request, file, filetransport.Options{
Filename: filename, CacheControl: "private, no-store",
}); err != nil {
logger.Errorf(ctx, "Failed to stream attachment preview: %v", err)
}
}
func (h *Handler) DeleteTemporaryDocument(c *gin.Context) {
ctx := c.Request.Context()
sessionID := sessionIDParam(c)
// Deleting mutates the session's attachments, so use the strict owner scope:
// a tenant admin may read an API-key session but must not remove attachments.
if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {
c.Error(apperrors.NewNotFoundError("Session not found"))
return
}
if err := h.temporaryDocuments.Delete(ctx, c.GetUint64(types.TenantIDContextKey.String()), sessionID, c.Param("attachment_id")); err != nil {
c.Error(apperrors.NewInternalServerError(err.Error()))
return
}
c.Status(http.StatusNoContent)
}
func sessionIDParam(c *gin.Context) string {
if value := c.Param("session_id"); value != "" {
return value
}
return c.Param("id")
}
func containsFileType(supported []string, ext string) bool {
for _, item := range supported {
if strings.TrimPrefix(strings.ToLower(strings.TrimSpace(item)), ".") == ext {
return true
}
}
return false
}
func isAudioExtension(ext string) bool {
switch ext {
case "mp3", "wav", "m4a", "flac", "ogg", "aac":
return true
default:
return false
}
}
@@ -0,0 +1,75 @@
package session
import (
"bytes"
"context"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type engineTestSessions struct{ interfaces.SessionService }
func (engineTestSessions) GetOwnedSession(context.Context, string) (*types.Session, error) {
return &types.Session{ID: "session-1", TenantID: 7}, nil
}
type engineTestDocuments struct {
interfaces.TemporaryDocumentService
options types.TemporaryDocumentCreateOptions
}
func (d *engineTestDocuments) Create(
_ context.Context, _ uint64, _, _, _ string, _ int64, _ io.Reader, options types.TemporaryDocumentCreateOptions,
) (*types.TemporaryDocument, error) {
d.options = options
return &types.TemporaryDocument{ID: "doc-1"}, nil
}
func uploadWithEngine(t *testing.T, h *Handler, agentID string) {
t.Helper()
body := &bytes.Buffer{}
form := multipart.NewWriter(body)
part, err := form.CreateFormFile("file", "report.pdf")
require.NoError(t, err)
_, _ = part.Write([]byte("%PDF-1.4"))
require.NoError(t, form.WriteField("parser_engine", "mineru_cloud"))
require.NoError(t, form.WriteField("agent_id", agentID))
require.NoError(t, form.Close())
c, ctx := newResolveAgentTestContext(7)
c.Params = gin.Params{{Key: "session_id", Value: "session-1"}}
req := httptest.NewRequest(http.MethodPost, "/", body).WithContext(ctx)
req.Header.Set("Content-Type", form.FormDataContentType())
c.Request = req
h.UploadTemporaryDocument(c)
require.Empty(t, c.Errors)
}
// A shared agent parses in its owner's workspace; the caller must not pick
// which of the owner's parser engines (and credentials) runs.
func TestUploadTemporaryDocumentIgnoresCallerEngineForSharedAgents(t *testing.T) {
shared := &engineTestDocuments{}
h := &Handler{
sessionService: engineTestSessions{},
temporaryDocuments: shared,
agentShareService: &resolveAgentShareStub{agent: &types.CustomAgent{ID: "shared-agent", TenantID: 84}},
customAgentService: &resolveOwnAgentStub{err: context.Canceled},
}
uploadWithEngine(t, h, "shared-agent")
require.Equal(t, uint64(84), shared.options.ResourceTenantID)
require.Empty(t, shared.options.ParserEngine)
own := &engineTestDocuments{}
h.temporaryDocuments = own
h.customAgentService = &resolveOwnAgentStub{agent: &types.CustomAgent{ID: "own-agent", TenantID: 7}}
uploadWithEngine(t, h, "own-agent")
require.Equal(t, "mineru_cloud", own.options.ParserEngine, "the caller's own workspace keeps its choice")
}
+89
View File
@@ -0,0 +1,89 @@
package session
import (
stderrors "errors"
"net/http"
"academy/internal/errors"
"academy/internal/logger"
"github.com/gin-gonic/gin"
)
// Use the validated request override, which has already been cleared when the
// conversation executes in another workspace. An empty result keeps the
// title service's existing default-model fallback.
func (rc *qaRequestContext) titleModelID() string {
if rc.summaryModelID != "" {
return rc.summaryModelID
}
if rc.customAgent != nil {
return rc.customAgent.Config.ModelID
}
return ""
}
// GenerateTitle godoc
// @Summary 生成会话标题
// @Description 根据消息内容自动生成会话标题
// @Tags 会话
// @Accept json
// @Produce json
// @Param session_id path string true "会话ID"
// @Param request body GenerateTitleRequest true "生成请求"
// @Success 200 {object} map[string]interface{} "生成的标题"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/{session_id}/title [post]
func (h *Handler) GenerateTitle(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start generating session title")
// Get session ID from URL parameter
sessionID := c.Param("session_id")
if sessionID == "" {
logger.Error(ctx, "Session ID is empty")
c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))
return
}
// Parse request body
var request GenerateTitleRequest
if err := c.ShouldBindJSON(&request); err != nil {
logger.Error(ctx, "Failed to parse request data", err)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
// Get session from database. Title generation writes the session row, so use
// the strict owner scope: a tenant admin may read an API-key session but must
// not be able to (re)generate its title.
session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
if err != nil {
if stderrors.Is(err, errors.ErrSessionNotFound) {
logger.Warnf(ctx, "Session not found, ID: %s", sessionID)
c.Error(errors.NewNotFoundError(err.Error()))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Call service to generate title
logger.Infof(ctx, "Generating session title, session ID: %s, message count: %d", sessionID, len(request.Messages))
title, err := h.sessionService.GenerateTitle(ctx, session, request.Messages, "")
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Return generated title
logger.Infof(ctx, "Session title generated successfully, session ID: %s, title: %s", sessionID, title)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": title,
})
}
@@ -0,0 +1,30 @@
package session
import (
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestTitleModelFollowsValidatedConversationSelection(t *testing.T) {
agent := &types.CustomAgent{Config: types.CustomAgentConfig{ModelID: "agent-model"}}
for _, tc := range []struct {
name string
selected string
agent *types.CustomAgent
want string
}{
{"input overrides agent", "input-model", agent, "input-model"},
{"input without agent", "input-model", nil, "input-model"},
{"absent or cleared override uses agent", "", agent, "agent-model"},
{"unconfigured agent keeps default fallback", "", &types.CustomAgent{}, ""},
{"no selection keeps default fallback", "", nil, ""},
} {
t.Run(tc.name, func(t *testing.T) {
rc := &qaRequestContext{summaryModelID: tc.selected, customAgent: tc.agent}
require.Equal(t, tc.want, rc.titleModelID())
require.Equal(t, "agent-model", agent.Config.ModelID, "selection must not rewrite agent settings")
})
}
}
+128
View File
@@ -0,0 +1,128 @@
package session
import (
"academy/internal/types"
)
// CreateSessionRequest represents a request to create a new session
// Sessions are now knowledge-base-independent and serve as conversation containers.
// All configuration (knowledge bases, model settings, etc.) comes from custom agent at query time.
type CreateSessionRequest struct {
Kind string `json:"kind,omitempty" enums:",assistant"`
// Title for the session (optional)
Title string `json:"title"`
// Description for the session (optional)
Description string `json:"description"`
// ProjectDir is an optional Lite host-sandbox binding. When set it must
// be an absolute path already present in the user-approved ProjectDirs
// list. Empty means the session gets an auto-allocated workspace.
ProjectDir string `json:"project_dir,omitempty"`
}
// GenerateTitleRequest defines the request structure for generating a session title
type GenerateTitleRequest struct {
Messages []types.Message `json:"messages" binding:"required"` // Messages to use as context for title generation
}
// MentionedItemRequest represents a mentioned item in the request
type MentionedItemRequest struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"` // "kb", "file", "tag", "mcp", "skill"
KBType string `json:"kb_type"` // "document" or "faq" (only for kb type)
KBID string `json:"kb_id"` // Parent knowledge base for file/tag mentions
KBName string `json:"kb_name"` // Display name for parent KB
ServiceID string `json:"service_id"` // Parent MCP service for MCP tool mentions
SkillName string `json:"skill_name"` // Preloaded agent skill name
}
// ImageAttachment represents an image in a chat request.
// Frontend sends base64 data in the Data field; the backend saves, runs VLM analysis,
// and populates URL/Caption before proceeding with the chat pipeline.
type ImageAttachment struct {
Data string `json:"data,omitempty"` // base64 data URI from frontend (data:image/png;base64,...)
URL string `json:"url,omitempty"` // serving URL after saving to storage
Caption string `json:"caption,omitempty"` // VLM analysis result (context-aware, single call)
}
// CreateKnowledgeQARequest defines the request structure for knowledge QA
type CreateKnowledgeQARequest struct {
// Query text; may be empty only when an image or file is attached
Query string `json:"query"`
// Selected knowledge base ID for this request
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
// Selected knowledge ID for this request
KnowledgeIDs []string `json:"knowledge_ids"`
// Whether agent mode is enabled for this request
AgentEnabled bool `json:"agent_enabled"`
// Selected custom agent ID (backend resolves shared agent and its workspace from share relation)
AgentID string `json:"agent_id"`
// Optional disambiguator; backend still verifies the share relation
AgentSourceTenantID uint64 `json:"agent_source_tenant_id,omitempty"`
// Browser source
LocalBrowserEnabled bool `json:"local_browser_enabled"`
// Whether web search is enabled for this request
WebSearchEnabled bool `json:"web_search_enabled"`
// Optional summary model ID for this request (overrides session default)
SummaryModelID string `json:"summary_model_id"`
// Per-request MCP services selected via @mention
MCPServiceIDs []string `json:"mcp_service_ids"`
// Per-request Skills selected via @mention
SkillNames []string `json:"skill_names"`
// @mentioned tag IDs (display/debug; scoped via MentionedItems)
TagIDs []string `json:"tag_ids"`
// @mentioned knowledge bases and files
MentionedItems []MentionedItemRequest `json:"mentioned_items"`
// Whether to disable auto title generation
DisableTitle bool `json:"disable_title"`
// Attached images for multimodal chat
Images []ImageAttachment `json:"images"`
// Attached files (documents, audio, etc.)
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"`
// Pre-uploaded session-scoped document IDs
AttachmentIDs []string `json:"attachment_ids,omitempty"`
// Source channel: "web", "api", "im", etc.
Channel string `json:"channel"`
SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"`
// QuestionOrigin is the knowledge source of a picked suggested question.
QuestionOrigin *types.QuestionOrigin `json:"question_origin,omitempty"`
// PageContext is the Academy page the user has open (agent mode only).
PageContext *types.PageContext `json:"page_context,omitempty"`
// AssistantAccess is the Academy assistant access level: read_only,
// confirm or auto_write. The workspace ceiling caps it; other agents
// ignore it.
AssistantAccess types.AssistantAccessLevel `json:"assistant_access,omitempty"`
// ReasoningEffort overrides thinking for this request; empty inherits the agent configuration.
ReasoningEffort string `json:"reasoning_effort,omitempty"`
}
// AttachmentUpload represents a file attachment upload from the client
type AttachmentUpload struct {
Data string `json:"data"` // Base64-encoded file content
FileName string `json:"file_name"` // Original filename
FileSize int64 `json:"file_size"` // File size in bytes
}
// SearchKnowledgeRequest defines the request structure for searching knowledge without LLM summarization
type SearchKnowledgeRequest struct {
Query string `json:"query" binding:"required"` // Query text to search for
KnowledgeBaseID string `json:"knowledge_base_id"` // Single knowledge base ID (for backward compatibility)
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // IDs of knowledge bases to search (multi-KB support)
KnowledgeIDs []string `json:"knowledge_ids"` // IDs of specific knowledge (files) to search
TagIDs []string `json:"tag_ids"` // Tag IDs for filtering within a single KB
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // Optional scoped tag mentions
// Optional overrides of the tenant retrieval config. Omitted fields keep it.
VectorThreshold *float64 `json:"vector_threshold,omitempty"` // Minimum vector similarity
KeywordThreshold *float64 `json:"keyword_threshold,omitempty"` // Minimum keyword score
MatchCount int `json:"match_count,omitempty"` // Number of results to return
DisableKeywordsMatch bool `json:"disable_keywords_match,omitempty"` // Vector recall only
DisableVectorMatch bool `json:"disable_vector_match,omitempty"` // Keyword recall only
Rerank *types.RerankOptions `json:"rerank,omitempty"` // Rerank override
}
// StopSessionRequest represents the stop session request
type StopSessionRequest struct {
MessageID string `json:"message_id" binding:"required"`
}
@@ -0,0 +1,99 @@
package session
import (
"context"
"academy/internal/application/access"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
)
type wikiFixerKBLookup interface {
GetKnowledgeBaseByIDOnly(ctx context.Context, id string) (*types.KnowledgeBase, error)
}
type wikiFixerKBSharePermission = access.KBShareLookup
func (h *Handler) resolveWikiFixerTenantScope(
ctx context.Context,
agent *types.CustomAgent,
currentTenantID uint64,
callerTenantRole types.TenantRole,
kbIDs []string,
) (*types.CustomAgent, uint64) {
return resolveBuiltinWikiFixerTenantScope(
ctx,
agent,
currentTenantID,
callerTenantRole,
kbIDs,
h.knowledgebaseService,
h.kbShareService,
)
}
func resolveBuiltinWikiFixerTenantScope(
ctx context.Context,
agent *types.CustomAgent,
currentTenantID uint64,
callerTenantRole types.TenantRole,
kbIDs []string,
kbLookup wikiFixerKBLookup,
kbShare wikiFixerKBSharePermission,
) (*types.CustomAgent, uint64) {
if !types.RunsInSharedKBWorkspace(agent) {
return agent, 0
}
if currentTenantID == 0 || len(kbIDs) != 1 || kbLookup == nil || kbShare == nil {
return agent, 0
}
kbID := kbIDs[0]
kb, err := kbLookup.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err != nil {
logger.Warnf(ctx, "wiki fixer: failed to resolve KB %s for shared scope: %v", secutils.SanitizeForLog(kbID), err)
return agent, 0
}
if kb == nil {
logger.Warnf(ctx, "wiki fixer: KB %s not found for shared scope", secutils.SanitizeForLog(kbID))
return agent, 0
}
if kb.TenantID == 0 || kb.TenantID == currentTenantID {
return agent, 0
}
permissions := access.NewKBSharePermissions(ctx, kbShare, currentTenantID, callerTenantRole)
allowed, err := permissions.Check(kb.ID, types.OrgRoleEditor)
if err != nil {
logger.Warnf(ctx, "wiki fixer: failed to check shared KB %s permission: %v", secutils.SanitizeForLog(kb.ID), err)
return agent, 0
}
if !allowed {
return agent, 0
}
scopedAgent := *agent
scopedAgent.TenantID = kb.TenantID
// The run now executes in the KB owner's workspace, where every ID and
// selection mode in the config resolves. The caller's own customizations
// (an "all" KB or MCP scope, skills, sandbox, models) would reach the
// owner's other resources, so start from the built-in defaults and pin
// the config to this one KB. Models fall back to the KB's own.
if builtin := types.GetBuiltinAgent(agent.ID, kb.TenantID); builtin != nil {
scopedAgent.Config = builtin.Config
}
scopedAgent.Config.KBSelectionMode = "selected"
scopedAgent.Config.KnowledgeBases = []string{kb.ID}
scopedAgent.Config.MCPSelectionMode = "none"
scopedAgent.Config.MCPServices = nil
scopedAgent.Config.SkillsSelectionMode = "none"
scopedAgent.Config.SelectedSkills = nil
scopedAgent.Config.SandboxConfigID = ""
scopedAgent.Config.WebSearchEnabled = false
scopedAgent.Config.ModelID = ""
scopedAgent.Config.RerankModelID = ""
scopedAgent.Config.VLMModelID = ""
logger.Infof(ctx, "wiki fixer: using shared KB source tenant %d for KB %s", kb.TenantID, secutils.SanitizeForLog(kb.ID))
return &scopedAgent, kb.TenantID
}
@@ -0,0 +1,212 @@
package session
import (
"context"
"errors"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
type wikiFixerKBLookupStub struct {
kb *types.KnowledgeBase
err error
calledWith string
}
func (s *wikiFixerKBLookupStub) GetKnowledgeBaseByIDOnly(_ context.Context, id string) (*types.KnowledgeBase, error) {
s.calledWith = id
return s.kb, s.err
}
type wikiFixerKBShareStub struct {
permission types.OrgMemberRole
isShared bool
err error
checkedKBID string
checkedTenantID uint64
checkedTenantRole types.TenantRole
}
func (s *wikiFixerKBShareStub) CheckTenantKBPermission(
_ context.Context,
kbID string,
callerTenantID uint64,
callerTenantRole types.TenantRole,
) (types.OrgMemberRole, bool, error) {
s.checkedKBID = kbID
s.checkedTenantID = callerTenantID
s.checkedTenantRole = callerTenantRole
return s.permission, s.isShared, s.err
}
func TestResolveBuiltinWikiFixerTenantScope_SharedEditorUsesSourceTenant(t *testing.T) {
agent := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 10, Name: "Wiki Fixer", IsBuiltin: true}
kbLookup := &wikiFixerKBLookupStub{
kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20, Name: "Shared KB"},
}
kbShare := &wikiFixerKBShareStub{
permission: types.OrgRoleEditor,
isShared: true,
}
gotAgent, effectiveTenantID := resolveBuiltinWikiFixerTenantScope(
context.Background(),
agent,
10,
types.TenantRoleContributor,
[]string{"kb-shared"},
kbLookup,
kbShare,
)
require.NotSame(t, agent, gotAgent)
require.Equal(t, uint64(20), gotAgent.TenantID)
require.Equal(t, uint64(20), effectiveTenantID)
require.Equal(t, uint64(10), agent.TenantID, "must not mutate the cached built-in agent")
require.Equal(t, "kb-shared", kbLookup.calledWith)
require.Equal(t, "kb-shared", kbShare.checkedKBID)
require.Equal(t, uint64(10), kbShare.checkedTenantID)
require.Equal(t, types.TenantRoleContributor, kbShare.checkedTenantRole)
}
// The scoped run executes in the owner's workspace, so the caller's own fixer
// customizations must not select the owner's other KBs, MCP services, skills
// or models there.
func TestResolveBuiltinWikiFixerTenantScope_PinsConfigToTheSharedKB(t *testing.T) {
agent := &types.CustomAgent{
ID: types.BuiltinWikiFixerID, TenantID: 10, IsBuiltin: true,
Config: types.CustomAgentConfig{
KBSelectionMode: "all",
MCPSelectionMode: "",
SkillsSelectionMode: "all",
SandboxConfigID: "caller-sandbox",
WebSearchEnabled: true,
ModelID: "caller-model",
},
}
kbLookup := &wikiFixerKBLookupStub{kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20}}
kbShare := &wikiFixerKBShareStub{permission: types.OrgRoleEditor, isShared: true}
gotAgent, _ := resolveBuiltinWikiFixerTenantScope(
context.Background(), agent, 10, types.TenantRoleContributor, []string{"kb-shared"}, kbLookup, kbShare,
)
cfg := gotAgent.Config
require.Equal(t, "selected", cfg.KBSelectionMode)
require.Equal(t, []string{"kb-shared"}, cfg.KnowledgeBases)
require.Equal(t, "none", cfg.MCPSelectionMode)
require.Equal(t, "none", cfg.SkillsSelectionMode)
require.Empty(t, cfg.SandboxConfigID)
require.False(t, cfg.WebSearchEnabled)
require.Empty(t, cfg.ModelID)
require.True(t, types.NewSharedAgentKBScope(gotAgent).Allows("kb-shared", 20))
require.False(t, types.NewSharedAgentKBScope(gotAgent).Allows("kb-other", 20))
require.Equal(t, "all", agent.Config.KBSelectionMode, "must not mutate the caller's agent")
}
func TestResolveBuiltinWikiFixerTenantScope_SharedViewerDoesNotSwitchTenant(t *testing.T) {
agent := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 10, IsBuiltin: true}
kbLookup := &wikiFixerKBLookupStub{
kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20},
}
kbShare := &wikiFixerKBShareStub{
permission: types.OrgRoleViewer,
isShared: true,
}
gotAgent, effectiveTenantID := resolveBuiltinWikiFixerTenantScope(
context.Background(),
agent,
10,
types.TenantRoleContributor,
[]string{"kb-shared"},
kbLookup,
kbShare,
)
require.Same(t, agent, gotAgent)
require.Zero(t, effectiveTenantID)
require.Equal(t, uint64(10), gotAgent.TenantID)
}
func TestResolveBuiltinWikiFixerTenantScope_IgnoresNonWikiFixerAgents(t *testing.T) {
agent := &types.CustomAgent{ID: "custom-agent", TenantID: 10}
kbLookup := &wikiFixerKBLookupStub{
kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20},
}
kbShare := &wikiFixerKBShareStub{
permission: types.OrgRoleEditor,
isShared: true,
}
gotAgent, effectiveTenantID := resolveBuiltinWikiFixerTenantScope(
context.Background(),
agent,
10,
types.TenantRoleContributor,
[]string{"kb-shared"},
kbLookup,
kbShare,
)
require.Same(t, agent, gotAgent)
require.Zero(t, effectiveTenantID)
require.Empty(t, kbLookup.calledWith)
}
func TestResolveBuiltinWikiFixerTenantScope_RequiresSingleKnowledgeBase(t *testing.T) {
agent := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 10, IsBuiltin: true}
kbLookup := &wikiFixerKBLookupStub{
kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20},
}
gotAgent, effectiveTenantID := resolveBuiltinWikiFixerTenantScope(
context.Background(),
agent,
10,
types.TenantRoleContributor,
[]string{"kb-a", "kb-b"},
kbLookup,
&wikiFixerKBShareStub{permission: types.OrgRoleEditor, isShared: true},
)
require.Same(t, agent, gotAgent)
require.Zero(t, effectiveTenantID)
require.Empty(t, kbLookup.calledWith)
}
func TestResolveBuiltinWikiFixerTenantScope_FallsBackOnLookupOrPermissionErrors(t *testing.T) {
agent := &types.CustomAgent{ID: types.BuiltinWikiFixerID, TenantID: 10, IsBuiltin: true}
t.Run("kb lookup error", func(t *testing.T) {
gotAgent, effectiveTenantID := resolveBuiltinWikiFixerTenantScope(
context.Background(),
agent,
10,
types.TenantRoleContributor,
[]string{"kb-shared"},
&wikiFixerKBLookupStub{err: errors.New("lookup failed")},
&wikiFixerKBShareStub{permission: types.OrgRoleEditor, isShared: true},
)
require.Same(t, agent, gotAgent)
require.Zero(t, effectiveTenantID)
})
t.Run("permission check error", func(t *testing.T) {
gotAgent, effectiveTenantID := resolveBuiltinWikiFixerTenantScope(
context.Background(),
agent,
10,
types.TenantRoleContributor,
[]string{"kb-shared"},
&wikiFixerKBLookupStub{kb: &types.KnowledgeBase{ID: "kb-shared", TenantID: 20}},
&wikiFixerKBShareStub{err: errors.New("permission failed")},
)
require.Same(t, agent, gotAgent)
require.Zero(t, effectiveTenantID)
})
}
@@ -0,0 +1,364 @@
package session
import (
"context"
"errors"
"strings"
"testing"
"time"
"academy/internal/agent/skills"
"academy/internal/application/service"
"academy/internal/event"
"academy/internal/sandbox"
"academy/internal/types"
"academy/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,
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")
}
// 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")
}